postfix rate limit 2

When sending large amounts of bulk emails, it may be necessary to enforce rate limiting to prevent the ISP’s from blocking your servers.

Reputation

In the world of high volume senders, a key metric for detecting spammers is the IP addresses’s reputation. Building a good reputation for your servers takes time and hence patience but it pays off with both delivery rate and performance, allowing you to send more email from a single resource.
Until you have good reputation, and to gain a better one to start with, it is recommended that you enforce rate limiting on your MTA. In this post I will focus on Postfix rate limiting, which I’m guessing is why you are here anyway.

The dreaded 421 error

Most email service provers allows you to send them emails at a certain unpublished rate. Some are politer than others, such as lets say, Yahoo, but when sending to a list of more than about 1000 recipients, it more than possible that you will face a temporary block. To prevent it from happening you should fine tune your postfix policy to create some form of delay between the emails that are sent to the same domain.
If you already encountered this error, it may look like:
Our system has detected an unusual rate of 421-4.7.0 unsolicited mail originating from your IP address. To protect our 421-4.7.0 users from spam, mail sent from your IP address has been temporarily 421-4.7.0 blocked. Please visit http://www.google.com/mail/help/bulk_mail.html 421 4.7.0 to review our Bulk Email Senders Guidelines.

Postfix rate limiting configuration

My first example will be of a global configuration and assumes that your server is handling only outgoing emails.
We need to edit the main.cf file and add the following lines:

smtp_destination_concurrency_limit = 2
smtp_destination_rate_delay = 1s
smtp_extra_recipient_limit = 10

Lets go over each line:
  • default_destination_concurrency_limit = 2
    This means that postfix will up to two concurrent connections per receiving domains.
    The default value is 20.
  • default_destination_rate_delay = 1s
    Postfix will add a delay between each message to the same receiving domain. It overrides the previous rule and in this example, it will send one email after another with a delay of 1 second. If you want to disable this rule, either delete it or set to 0.
  • default_extra_recipient_limit = 10
    Limit the number of recipients of each message. If a message had 20 recipients on the same domain, postfix will break it out to two different email messages instead of one.
Restart your postfix service and you are done.
If you are sending thousands of emails, and need to do so fairly quickly you will learn that this configuration will delay your rate considerably. Once you gain a better reputation, you will be able to move to the next step.

Different policies for different domains

Now, as you fine tune your policy, it may be apparent that some providers allow you to send emails at a higher rate, and some may need more delay between each message.
Lets create separate policies so we can optimise our server’s performance.
The first step will be to edit the master.cf file and add SMTP transports. Each transport will represent a policy for a group of receiving domain:

polite unix - - n - - smtp
turtle unix - - n - - smtp
Next, we need to map a domain to it’s transport name:
Edit the /etc/postfix/transport file and add the lines

gmail.com polite:
yahoo.com turtle:
hotmail.com polite:

Now we can add the policy to the master.cfmain.cf file:

transport_maps = hash:/etc/postfix/transport
polite_destination_concurrency_limit = 2
polite_destination_rate_delay = 0
polite_destination_recipient_limit = 5
turtle_destination_concurrency_limit = 1
turtle_destination_rate_delay = 3s
turtle_destination_recipient_limit = 2

Note that these values are just an example and you will have to tweak it yourself over time.
To activate these changes, we need to reload the postfix configuration:
postmap /etc/postfix/transport
service postfix restart
Read the ISP’s guidelines for bulk senders to better understand how to improve your reputation:

postfix recipient rate limit

Most of the renowned ESPs such as gmail or hotmail or yahoo do not like to mailed to from the same address multiple times in a short span. If they detect (and they will) that a server's IP is sending out bursts of emails in short span of time or over a single connection, they will most certainly block your IP.

Here is how we can negate this block by rate limiting on the server side so that the server IP(s) remain clean and unblocked. We can configure postfix to rate limit the mails based on their recipient domains. Suppose we need to rate limit mails to gmail to 1000 per hour, this can be achieved using the following steps.

We will use custom transports in postfix configuration to achieve this rate limiting. Custom transports are supported in postfix > v2.5. Check your postfix version using the following command:

    [root@smtp01 ~]# postconf mail_version
    mail_version = 2.8.5


If postfix is older than 2.5, upgrade it.

Now, define required additional transport in postfix master.cf file:

    smtp-gmail unix -    -    n    -    1    smtp
       -o syslog_name=smtp-gmail


syslog_name will specify the name by which messages related with this transport will be logged in maillog. This will help us to identify if the custom transport is working or not.

Define the required throttling (rate limits) settings in postfix main.cf

    smtp-gmail_destination_rate_delay = 12s
    smtp-gmail_destination_concurrency_limit = 1
    smtp-gmail_destination_recipient_limit = 2
    smtp-gmail_initial_destination_concurrency=1


The syntax is as follows: trasntport-name_variable-name=value

Here the transport name I am using is smtp-gmail. You can use anything of you own choice.

destination_rate_delay: This defines the delay between individual deliveries to the destination using this transport. Set this as per required. Suppose you want 10 deliveries per minute to gmail, then you can set it up like 60/10 = 6s.

destination_concurrency_limit: This decides the number of parallel deliveries to the destination using this transport. Setting it one means only one mail will be delivered once.

destination_recipient_limit: This decides the number of recipients per mail delivery. Setting this parameter to a value of 1 changes the meaning of the corresponding per-destination concurrency limit from concurrency per domain into concurrency per recipient. So set this to 2. This will take care of the domain. If you set it to 1, throttling will work only if you send mails to the same recipient and not for the same recipient domain.

initial_destination_concurrency: This decides the initial number of parallel deliveries. Default is 5, you don't want that probably, so set it as 1.

You can get more information about the parameters here: http://www.postfix.org/postconf.5.html

Create a transport map file, so that mails to gmail.com are directed to our new transport (smtp-gmail). Add the following to /etc/postfix/transport

    /\@gmail\.com$/       smtp-gmail:


The format of the above file is regexp. Lookups to regexp tables are fast so probably you should use those. For regexp to work you should have regexp support built into postfix. Find out using this command

    postconf -m


You should get the following result, showing all supported lookup tables

    [root@smtp01 ~]# postconf -m
    btree
    cidr
    environ
    hash
    internal
    ldap
    nis
    pcre
    proxy
    regexp
    static
    tcp
    texthash
    unix


Once the transport file is created, make sure to create the corresponding db, which will be actually used by postfix. Use postmap command.

    postmap  /etc/postfix/transport


Make postfix use this transport table. Edit main.cf and add the following:

    transport_maps = regexp:/etc/postfix/transport


Make sure you use regexp prefix.

Reload postfix.

Test the configuration.

Create a file containing two or more different gmail addresses. Then you can use a loop to send mails to them using the command line.

    for i in `cat recpts`; do echo "hello" | mail -s "testing throttling" $i; done


recpts is the file containing recipients' addresses.

Tail the maillog and grep for the transport name. You should get the following messages:

    Oct 5 10:33:26 smtp01 smtp-gmail/smtp[31905]: A8AB21EE201: to=, relay=gmail-smtp-in.l.google.com[209.85.143.27]:25, delay=1466, delays=0.09/1465/0.25/0.84, dsn=2.0.0, status=sent (250 2.0.0 OK 1317825206 ge19si1398564wbb.49)
    Oct 5 10:38:28 smtp01 smtp-gmail/smtp[31945]: AFF7B1EE206: to=, relay=gmail-smtp-in.l.google.com[209.85.143.26]:25, delay=1768, delays=0.09/1766/0.24/1.2, dsn=2.0.0, status=sent (250 2.0.0 OK 1317825508 s63si1405914weq.73)
    Oct 5 10:43:29 smtp01 smtp-gmail/smtp[31985]: B18DC1EE208: to=, relay=gmail-smtp-in.l.google.com[209.85.143.27]:25, delay=2069, delays=0.09/2068/0.25/0.75, dsn=2.0.0, status=sent (250 2.0.0 OK 1317825809 fn12si1423894wbb.51)
    Oct 5 10:48:30 smtp01 smtp-gmail/smtp[32021]: B136C1EE207: to=, relay=gmail-smtp-in.l.google.com[209.85.143.27]:25, delay=2370, delays=0.09/2369/0.25/0.48, dsn=2.0.0, status=sent (250 2.0.0 OK 1317826110 fi7si1433546wbb.71)


You can see that the transport 'smtp-gmail' is being called every five minutes ( as set in postfix main.cf).


Very good.
I prefer to have a separated transport file (maybe there are others maps involved):

transport_maps = hash:/etc/postfix/transport, regexp:/etc/postfix/transport_gmail

# cat /etc/postfix/transport_gmail
/\@gmail\.com$/ smtp-gmail:

No need to "postmap" this file.

Delay=2s caused transport invocation every 4 seconds in my experience.

I am pretty sure one does NOT use 'postmap' with regexp: type maps - postmap is only for hash:, dbm:, sdbm:, cdb:, btree: (ie. maps that require generation of indexed binary structures from the plain text source).

Icinga2 HTTPS and ssl key expiration check

Create a host file in /etc/icinga2/conf.d/hosts eg website-ripe.conf

Create the host details
object Host "website-ripe" {
  import "generic-host"
  address = "ripe.net"
  address6 = "::1"
  vars.os = "Linux"
  vars.sla = "24x7"
}


How to monitor a website over SSL (service)
object Service "httpS" {
  host_name = "website-ripe"
  vars.http_vhost = "ripe.net"
  vars.http_address = "193.0.6.139"
  vars.http_ssl = "1"
  vars.http_sni = "1"
  vars.http_warn_time = "5"
  vars.http_critical_time = "10"
  check_command = "http"
}

Monitoring the SSL key expiration date, give warning 30 before and alert at 14 days before. (service)
object Service "website-ripe-key-expire"{
  host_name = "website-ripe"
  check_command = "check-ssl-exp"
  vars.days = 30,14
  vars.url = "ripe.net"
}
Because it's not a default check -the -C (certificate) parameter is not available in Icinga- we need to create a custom checkCommand
object CheckCommand "check-ssl-exp" {
import "plugin-check-command"
command = PluginDir + "/check_http -H $url$ -C$daysquot;
}



Error:
[2014-07-30 12:58:00 +0200] critical/config:
Config error: Invalid value for attribute: Object 'check_ssl' (Type: 'CheckCommand') at /etc/icinga2/conf.d/hosts/website-ripe.conf:28 -> Attribute 'methods'
[2014-07-30 12:58:00 +0200] critical/config: 1 errors, 0 warnings.

Solution:
add   import "plugin-check-command" ot the oject checkcommand section.

unmount busy device

df -a

umount -l /mount/point

Icinga2 disable ping checks on specific hosts

Problem:

You have a server which does not answer ping etc.
Icinga2 marks the host as critical and you want to get rid of it.
Solution

By default, Icinga2 applies to every host the service ping4 or ping6 (depending on the address). This is done with an apply rule in
 /etc/icinga2/conf.d/services.conf:
apply Service "ping4" {
import "generic-service"
check_command = "ping4"
assign where host.address
}

To disable it for two specific host you only have to add an ignore rule (ping4):

ignore where match("x.x.x.x", host.address) || match("y.y.y.y", host.address)

example:-

ignore where match("1.2.3.4", host.address) || match("5.6.7.8", host.address)

remotedesktop using linux tool called rdesktop

rdesktop -k en-us -a 16 -g 90% -u Administrator -p 'P@ss#4dD'   192.168.1.100

mysql lock query timeout

show open tables where in_use>0;
SHOW VARIABLES LIKE 'tx_isolation';
or if you have MySQL 5.1+
SELECT * FROM information_schema.session_variables
WHERE variable_name = 'tx_isolation';
If you want to know what the server has configured globally, change the above to the following:
SHOW GLOBAL VARIABLES LIKE 'tx_isolation';
or if you have MySQL 5.1+
SELECT * FROM information_schema.global_variables
WHERE variable_name = 'tx_isolation';
If you want to make the query reveal what transaction isolation is being used, run this:
SELECT variable_value IsolationLevel
FROM information_schema.session_variables
WHERE variable_name = 'tx_isolation';**

mysql explain

https://mariadb.com/kb/en/mariadb/explain/

The columns in EXPLAIN ... SELECT

Column nameDescription
idSequence number that shows in which order tables are joined.
select_typeWhat kind of SELECT the table comes from.
tableAlias name of table. Materialized temporary tables for sub queries are named <subquery#>
typeHow rows are found from the table (join type).
possible_keyskeys in table that could be used to find rows in the table
keyThe name of the key that is used to retrieve rows. NULL is no key was used.
key_lenHow many bytes of the key that was used (shows if we are using only parts of the multi-column key).
refThe reference that is used to as the key value.
rowsAn estimate of how many rows we will find in the table for each key lookup.
ExtraExtra information about this join.
Here are descriptions of the values for some of the more complex columns in EXPLAIN ... SELECT:

"select_type" column

The select_type column can have the following values:
ValueDescription
PRIMARYThe SELECT is a PRIMARY one.
SIMPLEThe SELECT is a SIMPLE one.
DERIVEDThe SELECT is DERIVED from the PRIMARY.
SUBQUERYThe SELECT is a SUBQUERY of the PRIMARY.
DEPENDENT SUBQUERYThe SUBQUERY is DEPENDENT.
UNCACHEABLE SUBQUERYThe SUBQUERY is UNCACHEABLE.
UNIONThe SELECT is a UNION of the PRIMARY.
UNION RESULTThe result of the UNION.
DEPENDENT UNIONThe UNION is DEPENDENT.
UNCACHEABLE UNIONThe UNION is UNCACHEABLE.

"Type" column

This column contains information on how the table is accessed.
ValueDescription
ALLA full table scan is done for the table (all rows are read). This is bad if the table is large and the table is joined against a previous table! This happens when the optimizer could not find any usable index to access rows.
constThere is only one possibly matching row in the table. The row is read before the optimization phase and all columns in the table are treated as constants.
eq_refA unique index is used to find the rows. This is the best possible plan to find the row.
fulltextA fulltext index is used to access the rows.
index_mergeA 'range' access is done for for several index and the found rows are merged. The key column shows which keys are used.
index_subqueryThis is similar as ref, but used for sub queries that are transformed to key lookups.
indexA full scan over the used index. Better than ALL but still bad if index is large and the table is joined against a previous table.
rangeThe table will be accessed with a key over one or more value ranges.
ref_or_nullLike 'ref' but in addition another search for the 'null' value is done if the first value was not found. This happens usually with sub queries.
refA non unique index or prefix of an unique index is used to find the rows. Good if the prefix doesn't match many rows.
systemThe table has 0 or 1 rows.
unique_subqueryThis is similar as eq_ref, but used for sub queries that are transformed to key lookups

"Extra" column

This column consists of one or more of the following values, separated by ';'
Note that some of these values are detected after the optimization phase.
The optimization phase can do the following changes to the WHERE clause:
  • Add the expressions from the ON and USING clauses to the WHERE clause.
  • Constant propagation: If there is column=constant, replace all column instances with this constant.
  • Replace all columns from 'const' tables with their values.
  • Remove the used key columns from the WHERE (as this will be tested as part of the key lookup).
  • Remove impossible constant sub expressions. For example WHERE '(a=1 and a=2) OR b=1' becomes 'b=1'.
  • Replace columns with other columns that has identical values: Example: WHERE a=b and a=c may be treated as'WHERE a=b and a=c and b=c'.
  • Add extra conditions to detect impossible row conditions earlier. This happens mainly with OUTER JOIN where we in some cases add detection of NULL values in the WHERE (Part of 'Not exists' optimization). This can cause an unexpected 'Using where' in the Extra column.
  • For each table level we remove expressions that have already been tested when we read the previous row. Example: When joining tables t1 with t2 using the following WHERE 't1.a=1 and t1.a=t2.b', we don't have to test 't1.a=1' when checking rows in t2 as we already know that this expression is true.
ValueDescription
const row not foundThe table was a system table (a table with should exactly one row), but no row was found.
DistinctIf distinct optimization (remove duplicates) was used. This is marked only for the last table in the SELECT.
Full scan on NULL keyThe table is a part of the sub query and if the value that is used to match the sub query will be NULL, we will do a full table scan.
Impossible HAVINGThe used HAVING clause is always false so the SELECT will return no rows.
Impossible WHERE noticedafter reading consttables.The used WHERE clause is always false so the SELECT will return no rows. This case was detected after we had read all 'const' tables and used the column values as constant in the WHERE clause. For example: WHERE const_column=5 and const_column had a value of 4.
Impossible WHEREThe used WHERE clause is always false so the SELECT will return no rows. For example: WHERE 1=2
No matching min/max rowDuring early optimization of MIN()/MAX() values it was detected that no row could match the WHERE clause. The MIN()/MAX() function will return NULL.
no matching row in consttableThe table was a const table (a table with only one possible matching row), but no row was found.
No tables usedThe SELECT was a sub query that did not use any tables. For example a there was no FROM clause or a FROM DUAL clause.
Not existsStop searching after more row if we find one single matching row. This optimization is used with LEFT JOIN where one is explicitly searching for rows that doesn't exists in the LEFT JOIN TABLE. Example: SELECT * FROM t1 LEFT JOIN t2 on (...) WHERE t2.not_null_column IS NULL. As t2.not_null_column can only be NULL if there was no matching row for on condition, we can stop searching if we find a single matching row.
Open_frm_onlyFor INFORMATION_SCHEMA tables. Only the frm (table definition file was opened) was opened for each matching row.
Open_full_tableFor INFORMATION_SCHEMA tables. A full table open for each matching row is done to retrieve the requested information. (Slow)
Open_trigger_onlyFor INFORMATION_SCHEMA tables. Only the trigger file definition was opened for each matching row.
Range checked for eachrecord (index map: ...)This only happens when there was no good default index to use but there may some index that could be used when we can treat all columns from previous table as constants. For each row combination the optimizer will decide which index to use (if any) to fetch a row from this table. This is not fast, but faster than a full table scan that is the only other choice. The index map is a bitmask that shows which index are considered for each row condition.
Scanned 0/1/all databasesFor INFORMATION_SCHEMA tables. Shows how many times we had to do a directory scan.
Select tables optimizedawayAll tables in the join was optimized away. This happens when we are only using COUNT(*), MIN() and MAX() functions in the SELECT and we where able to replace all of these with constants.
Skip_open_tableFor INFORMATION_SCHEMA tables. The queried table didn't need to be opened.
unique row not foundThe table was detected to be a const table (a table with only one possible matching row) during the early optimization phase, but no row was found.
Using filesortFilesort is needed to resolve the query. This means an extra phase where we first collect all columns to sort, sort them with a disk based merge sort and then use the sorted set to retrieve the rows in sorted order. If the column set is small, we store all the columns in the sort file to not have to go to the database to retrieve them again.
Using indexOnly the index is used to retrieve the needed information from the table. There is no need to perform an extra seek to retrieve the actual record.
Using index conditionLike 'Using where' but the where condition is pushed down to the table engine for internal optimization at the index level.
Using index condition(BKA)Like 'Using index condition' but in addition we use batch key access to retrieve rows.
Using index for group-byThe index is being used to resolve a GROUP BY or DISTINCT query. The rows are not read. This is very efficient if the table has a lot of identical index entries as duplicates are quickly jumped over.
Using intersect(...)For index_merge joins. Shows which index are part of the intersect.
Using join bufferWe store previous row combinations in a row buffer to be able to match each row against all of the rows combinations in the join buffer at one go.
Using sort_union(...)For index_merge joins. Shows which index are part of the union.
Using temporaryA temporary table is created to hold the result. This typically happens if you are using GROUP BY, DISTINCT or ORDER BY.
Using whereA WHERE expression (in additional to the possible key lookup) is used to check if the row should be accepted. If you don't have 'Using where' together with a join type of ALL, you are probably doing something wrong!
Using where with pushedconditionLike 'Using where' but the where condition is pushed down to the table engine for internal optimization at the row level.
Using bufferThe UPDATE statement will first buffer the rows, and then run the updates, rather than do updates on the fly. See Using Buffer UPDATE Algorithm for a detailed explanation.

EXPLAIN EXTENDED

The EXTENDED keyword adds another column, filtered, to the output. This is a percentage estimate of the table rows that will be filtered by the condition.
An EXPLAIN EXTENDED will always throw a warning, as it adds extra Message information to a subsequent SHOW WARNINGSstatement. This includes what the SELECT query would look like after optimizing and rewriting rules are applied and how the optimizer qualifies columns and tables.