Links: 20 Sep

Technology

Other

> How about a sysctl that does “for the love of kbaek, don’t ever kill these
> processes when OOM. If nothing else can be killed, I’d rather you panic”?

An aircraft company discovered that it was cheaper to fly its planes with less fuel on board. The planes would be lighter and use less fuel and money was saved. On rare occasions however the amount of fuel was insufficient, and the plane would crash. This problem was solved by the engineers of the company by the development of a special OOF (out-of-fuel) mechanism. In emergency cases a passenger was selected and thrown out of the plane. (When necessary, the procedure was repeated.) A large body of theory was developed and many publications were devoted to the problem of properly selecting the victim to be ejected. Should the victim be chosen at random? Or should one choose the heaviest person? Or the oldest? Should passengers pay in order not to be ejected, so that the victim would be the poorest on board? And if for example the heaviest person was chosen, should there be a special exception in case that was the pilot? Should first class passengers be exempted? Now that the OOF mechanism existed, it would be activated every now and then, and eject passengers even when there was no fuel shortage. The engineers are still studying precisely how this malfunction is caused.

Remember measles? That old-timey disease we officially eliminated in the United States 13 years ago? Thanks to the wonder of inoculation, measles should be entirely nonexistent in this country, but yesterday the Center for Disease Control reported 159 cases from January through August of this year.

What’s unique about this year’s outbreak is that the CDC has finally admitted the spread of this “eliminated” disease is based on religious communities’ philosophical aversion to vaccines and reliance on divine healing through the Word of God. According to the report, 91 percent of the reported cases were in people who were unvaccinated, or didn’t know their vaccination status, and “of those who were unvaccinated, 79 percent had philosophical objections to vaccination.”

  • London Heathrow’s glissade timelapse:

 

 

Links: 4 Sep

Technology:

  • grep tricks: grep files recursively, show only filenames where matching string was/wasn’t found.
  • Did you know that:
    • $ less <directory> — shows directory listing
    • $ less <archive.zip> — shows archive content
  • Teacher’s rumblings “Kids can’t use computers“. Agree to a T.
  • Going back to iPhone [from Android]. Again having pretty much the same thoughts.
  • Reddit: Lessons Learned From Mistakes Made Scaling To 1 Billion Pageviews A Month
  • Start a Web Search in a GUI Browser from the Command Line on Mac OS X
  • Screen recording to an animated GIF on Mac OS X
  • How to know from a child process that its parent exited:
    • a pipe between parent and a child, child gets SIGPIPE when parent exits
    • if a child has not detached, PPID becomes 1 when parent exits
    • Linux-specific: a child can ask kernel to deliver a signal when parent dies by specifying option PR_SET_PDEATHSIG in prctl() syscall
  • Two talks from YAC which I liked:

rpmdb locking issues, notorious on RHEL4/5, manifest as hanging rpm command. To see active locks:

# cd /var/lib/rpm; /usr/lib/rpm/rpmdb_stat -CA

Normally there should be no locks, given no rpm command is running. In case there are stale locks, just remove __db.00* files.

Other:

Sunlight in Europe and the USA in hours per year.

Links: 16 Aug

Technology:

  • Cloud server showdown: Amazon AWS EC2 vs Linode vs DigitalOcean. AWS performance sucks, Linode winner.
  • Pull mode in orchestration’s rising star, Ansible. Check also out the web interface — AnsibleWorks AWX
  • Learning from other disciplines, nice quote:

    I’ve seen several college of engineering departments that have a sign that says the equivalent of, “If you cheat in engineering classes, you will kill people later”. We don’t have that mindset yet with IT, but I think we should because eventually, we’ll be responsible for infrastructure that will kill people if we get it wrong.

  • knockd — a port-knock server. It listens to all traffic on an ethernet (or PPP) interface, looking for special “knock” sequences of port-hits. A client makes these port-hits by sending a TCP (or UDP) packet to a port on the server. When the server detects a specific sequence of port-hits, it runs a command defined in its configuration file. This can be used to open up holes in a firewall for quick access.
  • Here’s the example of why LISA conferences rock: 2007 paper On Designing and Deploying Internet-Scale Services. Must read for sysadmins.
  • How to automatically setup and keep ssh tunnel up with autossh, available from macports

Social:

  • Steven Fry, one of my all-time favourite actors and activists, wrote an open letter petitioning for moving Winter Olimpics 2014 from Russia to elsewhere, because of wilful LGBT community oppressions. On a related note, sexual orientation forms during prenatal period, influenced by hormone levels, and is therefore inborn feature. Read about it in Russian.

 

 

 

Links: 3 Aug

Technology

English

Ghosting—aka the Irish goodbye, the French exit, and any number of other vaguely ethnophobic terms—refers to leaving a social gathering without saying your farewells. One moment you’re at the bar, or the house party, or the Sunday morning wedding brunch. The next moment you’re gone.

Republicans are also better, Democrats fear, at agreeing on a message and sticking to it. Frank Luntz, a Republican consultant, once said: “There’s a simple rule. You say it again, and you say it again, and you say it again, and you say it again, and you say it again, and then again and again and again and again, and about the time that you’re absolutely sick of saying it is about the time that your target audience has heard it for the first time.”

 

 

 

Links: 21 July

Technology

Education

My most favourite coursera course Algorithms by Kevin Wayne and Robert Sedgewick of Princeton is coming back with new session this autumn; my passionate recommendation to take it if you’re doing any kind of programming, either to improve your skills or just get a lot of fun:

Bootstrap-related

IT in Ukraine (in Russian)

Miscellaneous

Petit Fille, liked choreography a lot:

Links: 14 July

Technology

  • Three ways how to get Apache to automatically insert the Google Analytics script into every page on the fly.
  • SSL: Intercepted today, decrypted tomorrow — recently leaked documents appear to reveal that the NSA logs very high volumes of internet traffic and retains captured encrypted communication for later cryptanalysis. The reason […] is that if the SSL private key to the encrypted traffic later becomes available — perhaps through court order, social engineering, successful attack against the website, or through cryptanalysis — all of the affected site’s historical traffic may then be decrypted at once.
  • First 5 Minutes Troubleshooting A Server, great post, Russian translation is here.
  • Swagger is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services.

English

 

Первые 5 минут устранения неполадок на сервере

Винсент Виалле

First 5 Minutes Troubleshooting A Server by Vincent Viallet, 6 March 2013
Original post: http://devo.ps/blog/2013/03/06/troubleshooting-5minutes-on-a-yet-unknown-box.html

Translated by Ivan Pesin, July 2013

Когда наша команда еще занималась вопросами эксплуатации, оптимизации и масштабирования в предыдущей компании, нам приходилось иметь дело с отладкой медленно работающих приложений и целых инфраструктур, часто большого размера (представьте CNN или the World Bank). Горящие сроки, экзотические стеки технологий и недостаток информации обычно гарантировали незабываемые впечатления.

Причины неполадок редко были очевидными; ниже я привожу список шагов, с которых мы обычно начинали поиск проблемы.

Войдите немного в контекст

Не спешите бросаться на сервера, сперва нужно выяснить, что уже известно о системе и специфике проблемы. Не стоит тратить время на поиск проблемы вслепую.

Несколько обязательных вопросов, требующих ответа:

  • Какие конкретно наблюдаются симптомы? Подвисания? Ошибки?
  • Когда проблема была замечена впервые?
  • Воспроизводится ли она?
  • Есть ли закономерность (например, происходит каждый час)?
  • Какие были последние изменения в системе (код, сервисы, стек приложений)?
  • Влияет ли проблема на определенную группу пользователей (авторизированных, не авторизированных, с общим географическим расположением…)?
  • Имеется ли документация на архитектуру (физическую и логическую)?
  • Используется ли система мониторинга? Munin, Zabbix, Nagios, New Relic… Подойдет любая.
  • Ведется ли (централизированное) журналирование? Loggly, Airbrake, Graylog…

Последние два пункта представляют собой наиболее удобные источники информации, но не возлагайте на них больших надежд: как ни печально, именно мониторинг и журналирование часто отсутствуют. Если не повезло, сделайте заметку, что это нужно поправить, и двигайтесь дальше.

Кто здесь?

Не критично, но обычно не стоит заниматься устранением неполадок в системе, в то время когда с ней играются другие люди. На кухне достаточно одного повара.

Что делали в системе?

Всегда полезно посмотреть на историю команд в комбинации с информацией о том, кто ранее заходил в систему. Не забывайте про ответственность: то, что вы администратор, не дает вам права нарушать чужую конфиденциальность.

Маленькая заметка в уме на потом — вы можете задать переменную окружения HISTTIMEFORMAT, чтобы была возможность отслеживать время, когда выполнялись команды из истории. Нет ничего более раздражающего, чем анализ устаревшего списка команд, не имеющих отношения к проблеме…

 Что запущено?

Вывод ps aux содeржит, как правило, много подробной информации о процессах, тогда как pstree -a выдает наглядную и лаконичную картину запущенных процессов, вместе с родительской иерархией.

«Слушающие» сервисы

Я предпочитаю выполнять эти команды отдельно, в основном потому что я не люблю смотреть на все сервисы одновременно. Тем не менее, netstat -nalp тоже подойдет и я бы не опускал опцию -n  (IP-адреса, мне кажется, воспринимаются лучше).

Определите запущенные службы и выясните должны ли они выполнятся. Посмотрите какие порты находятся в слушающем состоянии. PID слушающего процесса можно всегда найти в выводе ps aux. Это может оказаться очень полезным, особенно когда в системе одновременно запущены несколько Java или Erlang процессов.

Обычно, мы стараемся, чтобы наши системы были более или менее специализированы, с небольшим количеством сервисов на каждой из них. Если вы видите десятки слушающих портов, наверно стоит отметить это себе в уме, чтобы потом разобраться как это можно почистить или реорганизовать.

Процессор и память

Эти команды должны ответить на несколько вопросов:

  • Есть ли свободная память? Происходит ли своппинг на диск?
  • Насколько загружены процессоры? Сколько ядер доступно на сервере? Перегружены ли какие-то из них?
  • Что больше всего нагружает систему? Какое у системы значение средней нагрузки (load average)?

Аппаратная часть

Обычные, невиртуализированные сервера продолжают широко использоваться, и эти команды должны помочь:

  • Определить RAID-контроллер (есть ли у него батарея резервного питания?), процессор и количество доступных слотов памяти. Это может подсказать вам потенциальные причины проблемы и пути увеличения производительности.
  • Выяснить правильно ли настроена сетевая карта? Не работает ли она в режиме полудуплекса? На скорости 10MBps? Есть ли ошибки приема-передачи?

Производительность ввода-вывода

Очень полезные команды для анализа общей производительности системы хранения.

  • Проверяем свободное место: есть ли в системе полностью занятые файловые системы или диски?
  • Используется ли своп (si/so)?
  • Что занимает процессор: системные вызовы? пользовательские процессы? много ли времени крадется гипервизором (VM)?
  • Моя любимая команда — dstat. Какие процессы интенсивно используют ввод-вывод? Может быть MySQL грузит дисковую подсистему? Или это какой-то PHP-скрипт?

Точки монтирования и файловые системы

  • Сколько файловых систем смонтировано?
  • Есть ли файловые системы, выделенные для конкретных сервисов? (MySQL например?)
  • Какие указаны опции монтирования: noatime? default? Есть ли какие-то файловые системы смонтированные в режиме только для чтения?
  • Есть ли свободное место на дисках?
  • Нет ли больших удаленных файлов, которые продолжают удерживаться каким-либо процессом?
  • Есть ли место для расширения раздела, если проблема в свободном пространстве?

Ядро, прерывания и сеть

  • Распределены ли прерывания равномерно по всем процессорам? Возможно одно из ядер перегружено из-за прерываний от сетевой карты, RAID-контроллера, …?
  • Какое задано значение swappinness в системе? 60 подходит для персональных компьютеров, но не для серверов. Желательно, чтобы сервер никогда не использовал своп, иначе во время чтения/записи данных на диск, процессы вытесненные в своп окажутся заблокированными.
  • Достаточно ли велико значение conntrack_max для существующего трафика?
  • Как долго TCP-соединения могут находится в различных состояниях (TIME_WAIT, …)?
  • netstat может быть немного медленным при выводе всех существующих соединений, тогда используйте ss -s, чтобы быстро получить краткую статистику.

Посмотрите статью про настройку TCP в Linux, в ней есть полезная информация на эту тему.

Системные журналы и сообщения ядра

  • Ищите любые сообщение об ошибках или предупреждения. Есть ли сообщения о слишком большом количестве соединений в conntrack?
  • Есть ли сообщения об аппаратных ошибках или ошибках файловой системы?
  • Коррелируется ли время между ошибками в журналах и предоставленной информацией о проблеме?

Задания cron

  • Есть ли задания, которые выполняются слишком часто?
  • Есть ли персональные конфигурационные файлы cron, спрятанные от постороннего взгляда?
  • Выполнялось ли какое-либо резервное копирование в то время, когда возникла проблема?

Журнальные файл приложений

Здесь можно много что исследовать, но вряд ли у вас будет время, чтобы детально все просмотреть. Поэтому, сконцентрируйтесь на самом очевидном, например для LAMP-сервера:

  • Apache & Nginx; посмотрите журналы доступа и ошибок, ищите ошибки 5xx, возможные ошибки limit_zone.
  • MySQL; посмотрите есть ли ошибки в mysql.log, следы поврежденных таблиц, работающий процесс восстановления innodb. Посмотрите журнал медленных операций и определите есть ли проблемы с диском, индексами или запросами.
  • PHP-FPM; если включен журнал php-slow, покопайтесь в нем и попробуйте найти ошибки (php, mysql, memcache, …). Если журнал выключен, активируйте его.
  • Varnish; проверьте отношение hit/miss в varnishlog и varnishstat. Не пропущено ли правило в конфигурации, в результате чего запросы конечных пользователей проходят до бекэнда, минуя varnish?
  • HA-Proxy; какой статус у бекэндов? Правильно ли работает проверка здоровья бекэндов? Не переполнена ли очередь запросов на фронтэнде или бекэндах?

Заключение

После этих первых пяти минут (плюс-минус десять), у вас должно будет сформироваться более полное понимание ситуации:

  • Что запущено.
  • Связана ли проблема с вводом-выводом/аппаратной частью/сетевой подсистемой или конфигурацией (плохой код, настройки ядра, …).
  • Есть ли знакомые шаблоны: плохое использование индексов БД, слишком много процессов apache, и т.п.

Вы даже могли уже найти непосредственную причину проблемы. Если нет, то вы находитесь в хорошей позиции для дальнейших поисков, зная, что все очевидное уже проверено.

 

The Elements of Style

The Elements of Style (4th Edition): William Strunk, E. B. White, Roger Angell: 9780205313426: Amazon.com: Books

The Elements of Style (4th Edition): William Strunk, E. B. White, Roger Angell: 9780205313426: Amazon.com: Bookshttp://www.amazon.com/The-Elements-Style-4th-Edition/dp/0205313426/“No book in shorter space, with fewer words, will help any writer more than this persistent little volume.” — The Boston Globe

A friend recommended a book to read, “The Elements of Style” by W. Strunk. It resonated with me strongly, here are few quotes:

Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences, for the same reason that a drawing should have no unnecessary lines and a machine no unnecessary parts. This requires not that the writer make all sentences short, or avoid all detail and treat subjects only in outline, but that every word tell.

“Do not join independent clauses with a comma.” (Rule 5.) “Do not break sentences in two.” (Rule 6.) “Use the active voice.” (Rule 14.) “Use definite, specific, concrete language.” (Rule 16.) “Omit needless words.” (Rule 17.) “Avoid a succession of loose sentences.” (Rule 18.)

The book advocates and illustrates how to write forcibly, clearly, and succinctly; something I value and aspire to incredibly in all sorts of communication, but also in thinking. The book’s volume, 85 less-than-A5 pages, reinforces the message and makes it ideal manual to keep at hand.

Link to the on-line version of the book: http://www.keck.ucsf.edu/~craig/The_Elements_of_Style.html

The Elements of Style - Wikipedia, the free encyclopedia

The Elements of Style – Wikipedia, the free encyclopediahttps://en.wikipedia.org/wiki/The_Elements_of_StyleThe Elements of Style (1918), by William Strunk, Jr. and E. B. White, is a prescriptive American English writing style guide comprising eight “elementary rules of usage”, ten…

vim syntax highlighting for cfengine3

Major part of my work these days is connected with cfengine3 and writing promises. I’m kind of a vim-guy, so clearly I’m using it when writing cfengine promises and when you write a lot of code, you’d definitely want to make your development environment comfy and snug. Part of being comfy and sung in my understanding is syntax highlighting, which tremendously simplifies reading code and makes you spot typos and other sorts of mistakes right away.

There’s an initial version of syntax highlighting for cfeninge, written by Neil Watson available on github. However, I wanted more sophisticated highlighting functionality, so I took Neil’s work and spent couple of weekends extending it. Here are some screenshots with results of that extension (click to see them full-size):


At the moment, the module highlights correctly cfengine-stdlib.cf and all cf files in examples/ directory of cfengine with exception of knowledge-related promises. There’s still a lot of work to do – a bit of refactoring and then, perhaps, a rudimental syntax checker – but it seems to me already usable, so I decided to release it’s “first” version.

The syntax highlighting module is available at https://github.com/ivanpesin/vim_cf3/tree/master/syntax. To activate it, you’ll need to save cf3.vim in ~/.vim/ directory and add following lines to your ~/.vimrc:

 

Bundle execution time randomization in cfengine3

Read this article in Russian.

In our environment we use cfengine to manage servers across the organization. Having a fairly large infrastructure we have to give a lot of thought to such things as smoothing the load on cfengine hubs and other parts of the infrastructure.

This article presents some approaches to bundle execution time randomization. This might be useful when you have a bundle which is going to affect a lot of servers and you don’t want it to execute simultaneously across a whole lot, thus causing a pressure point and possible event storms.

The first approach which comes to mind is splayclass() function, which defines a class if the system clock lies within a scheduled time-interval that maps to a hash of the first argument – arbitrary string, usually set to fqdn. Different strings will hash to different time intervals, and thus one can map different tasks to time-intervals. The code utilizing this function looks like this:

This will execute report at a random moment every hour.

A nuisance with this function is that it’s somewhat limited, having only “hourly” and “daily” policies. With “hourly” policy, the class will be defined for a 5-minute interval every hour, and with “daily” policy then the class will be defined for one 5-minute interval every day. This might be either too frequent or too seldom for a specific case. This also might be a problem if you use an cfengine run interval different from a default one.

To address this nuisance we might employ dist keyword in classes’ definition which generates a probabilistic class distribution. For example:

In this example class “percent_of_runs_15”  will be defined in 15 out of (15+85=) 100 cases or in 15% of cf-agent runs. Considering that cf-agent runs with 5 minutes interval by default, that makes 15% out of (24*12 =) 288 runs per day, or 43 runs, or approximately twice per hour at a random moment. Tuning the sum and the initial number we might change the random frequency at which the class will get defined.

Dist might give us even more flexibility, for example when we need the bundle to execute at the random hour every 12 hours, but at that hour we’d like bundle to run every 5 minutes. This might be needed when bundle requires multiple runs to fix things (deleting stuff from a file is a good example). So for that matter we might combine dist keyword with persistent classes, like in:

This approach seems to be more flexible, but it also contains an issue – due to its nature, dist is probabilistic and that means it doesn’t guarantee that the percent of distribution will be exact. In fact, you should keep in mind that +/- error is a norm here and, for instance, running the 15%/85% example drew results from 13% to 18% for 15% class.

We can also apply the approach with persistent classes to splayclass() function in the following manner:

Which would allow us to execute a report (or bundle) every 5 mins throughout a random hour of the day.