Статьи

Архив журналов и анализ с помощью Amazon S3 и Glacier — Часть III

  Резюме из предыдущих постов:

  • Мы видели, как настроить CloudFront для включения журналов доступа . CloudFront будет напрямую загружать все журналы доступа в настроенную корзину S3
  • Мы увидели, что нужно учитывать при ведении журналов на веб-уровне, таких как локальное хранилище журналов, динамическая среда. Мы настроили инстансы EC2 для использования Ephemeral Storage для локального хранения файлов журнала

В этом посте мы увидим, как проталкивать журналы из локального хранилища в центральное хранилище журналов — Amazon S3 и каковы его соображения.

Структура папок Amazon S3

Журналы будут создаваться в течение дня, и поэтому нам нужна правильная структура папок для их хранения в S3. Журналы будут особенно полезны для выполнения анализа, такого как производственная проблема, или для поиска модели использования, такой как принятие функции пользователями / месяц. Следовательно, имеет смысл хранить их по структуре year / month / day / hour_of_the_day.

Несколько экземпляров

Веб-уровень будет автоматически масштабирован, и у нас всегда будут работать несколько экземпляров для обеспечения высокой доступности и масштабируемости. Таким образом, даже если у нас есть журналы, хранимые ежечасно, у нас будут файлы журналов с похожими именами из нескольких экземпляров. Следовательно, структура папок также должна учитывать несколько экземпляров. Результирующая структура папок в S3 будет выглядеть примерно так

Структура папки журнала Amazon S3
Структура папки журнала Amazon S3

Обратите внимание, что на рисунке выше (как обведено кружком) мы храним мудрые журналы «Экземпляр» каждый час.

Вращение

журналов Каждая структура журналирования будет иметь возможность вращать файлы журналов по размеру, дате и т. Д. Мы будем периодически отправлять файлы журналов в Amazon S3, и, следовательно, имеет смысл сказать, что файл журнала вращается каждый час и нажмите на S3. Но недостатком этого является то, что мы не можем предвидеть трафик к веб-уровню, и именно поэтому мы автоматически масштабируем веб-уровень по требованию. Если в трафике произойдет внезапный скачок, который может привести к созданию больших файлов журнала, он начнет заполнять файловую систему, что в конечном итоге сделает экземпляр недоступным. Следовательно, лучше вращать файлы журнала по размеру.

Linux-logrotate

Вы можете использовать по умолчанию
logrotate доступен в системах Linux для поворота файлов журнала по размеру. Logrotate может быть настроен для вызова пост-скрипта после ротации, чтобы мы могли выдвигать вновь повернутые файлы на S3. Пример реализации logrotate будет выглядеть следующим образом:

Примечание. Если вы используете logrotate, убедитесь, что ваша структура ведения журнала не настроена на вращение

/var/log/applogs/httpd/web {
        missingok
        rotate 52
        size 50M
        copytruncate
        notifempty
        create 644 root root
        sharedscripts
        postrotate
                /usr/local/admintools/compress-and-upload.sh web &> /var/log/custom/web_logrotate.log
        endscript
}

The above set of commands rotate the «httpd» log files whenever the size reaches 50M. It also calls a «postrotate» script to compress the rotated file and upload it to S3.
Upload to S3

The next step is to upload the rotated log file to S3.

  • We need a mechanism to access the S3 API from the shell to upload the files. S3cmd is a command line tool that is widely used and recommended for accessing all S3 APIs through the command line. We need to setup the CLI in the Instance
  • We are rotating by size but we will be uploading to a folder structure that maintains log files by the hour
  • We will also be uploading from multiple Instances and hence we need to fetch the Instance Id to store in the corresponding folder. Within EC2, there is an easy way to get Instance meta data. If we «wget» «http://169.254.169.254/latest/meta-data/» it will provide the Instance meta-data such as InstanceId, public DNS, etc.. For example if we «wget» «http://169.254.169.254/latest/meta-data/instance-id» we will get the current Instance Id

The following set of commands will compress the rotated file and upload them into the corresponding S3 bucket

# Perform Rotated Log File Compression
tar -czPf /var/log/httpd/"$1".1.gz /var/log/httpd/"$1".1

# Fetch the instance id from the instance
EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`"
if [ -z $EC2_INSTANCE_ID ]; then
echo "Error: Couldn't fetch Instance ID .. Exiting .."
exit;
else
        # Upload log file to Amazon S3 bucket
        /usr/bin/s3cmd -c /.s3cfg put /var/log/httpd/"$1".1.gz s3://$BUCKET_NAME/$(date +%Y)/$(date +%m)/$(date +%d)/$EC2_INSTANCE_ID/"$1"/$(hostname -f)-$(date +%H%M%S)-"$1".gz
fi
# Removing Rotated Compressed Log File
rm -f /var/log/httpd/"$1".1.gz
Run While Shutdown

Since the web tier will automatically scale depending upon the load, Instances can be pulled off (terminated) when load decreases. During such scenarios, we might be still left with some log files (maximum of 50MB) that didn’t get rotated and uploaded. During shutdown, we can have a small script, that will forcefully call the logrotate to rotate the final set of files, compress and upload.

stop() {
echo -n "Force rotation of log files and upload to s3 intitiated"
/usr/sbin/logrotate -f /etc/logrotate.d/web
exit 0
}

Use IAM

We need to provide Access Key and Secret Access Key to the S3cmd utility for S3 API access. Do NOT provide the AWS account’s Access Key and Secret Access Key. Create an IAM user who has access to only the specific S3 bucket where we are uploading the files and use the IAM user’s Access Key and Secret Access Key. A sample policy allowing access for the IAM user to the S3 log bucket would be

{
  "Statement": [
    {
      "Sid": "Stmt1355302111002",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::"
      ]
    }
  ]
}
  • The above policy allows the IAM user to perform all actions on the S3 bucket. The user will not have permission to access any other buckets or services
  • If you want to restrict further, instead of allowing all actions on the S3 bucket, we can allow only PutObject (s3:PutObject) for uploading the files
  • Through the above approach, you will be storing the IAM credentials on the EC2 Instance itself. An alternative approach is to use IAM Roles so that the EC2 Instance will obtain the API credentials at runtime
With that we have the web tier log files automatically getting rotated, compressed and uploaded to Amazon S3 and stored in a central location. We have access to log information by the year/month/day/hour and Instance-wise.