program story

Linux cron 작업을 "Amazon 방식"으로 변환하는 방법은 무엇입니까?

inputbox 2020. 7. 29. 08:10
반응형

Linux cron 작업을 "Amazon 방식"으로 변환하는 방법은 무엇입니까?


더 좋든 나쁘 든 전체 LAMP 웹 응용 프로그램을 전용 컴퓨터에서 클라우드 (Amazon EC2 컴퓨터) 로 마이그레이션했습니다 . 지금까지는 훌륭하지만 크론 을 수행하는 방식 은 최적이 아닙니다 . "Amazon 방식"을 사용하여 클라우드에서 cron 작업을 가장 잘 관리하는 방법에 대한 Amazon 관련 질문이 있습니다.

문제 : 우리는 여러 개의 웹 서버를 가지고 있으며 RSS 피드 생성, 이메일 트리거링, 실제로 여러 가지 일과 같은 배치 작업을 위해 크론을 실행해야합니다. 그러나 크론 작업 종종 데이터베이스에 쓰므로 여러 머신에서 실행될 경우 결과를 복제하므로 한 머신에서만 실행 하면됩니다.

지금까지 웹 서버 중 하나를 "마스터 웹 서버"로 지정했으며 다른 웹 서버에는없는 몇 가지 "특별한"작업이 있습니다. 클라우드 컴퓨팅의 균형은 신뢰성입니다. 단일 마스터 지점이기 때문에 "마스터 웹 서버"를 원하지 않습니다. 우리는 클러스터에서 마스터 웹 서버를 사용하지 않는 것을 기억하지 않고 모두 동일하고 업 스케일 및 다운 스케일 할 수 있기를 원합니다.

Linux cron 작업을 단일 실패 지점이없는 일시적인 작업 항목으로 변환하도록 애플리케이션을 어떻게 재 설계 할 수 있습니까?

내 아이디어는 지금까지 :

  • 크론 만 운영하는 기계를 준비하십시오. 이것은 좀 더 관리하기는 쉽지만 여전히 단일 실패 지점이되고 여분의 인스턴스를 갖는 돈을 낭비하게됩니다.
  • 일부 작업은 Linux 크론에서 MySQL 이벤트 로 옮길 수 있지만 응용 프로그램 논리를 데이터베이스 계층에 넣고 싶지 않기 때문에이 아이디어를 좋아하지 않습니다.
  • 아마도 모든 머신에서 모든 크론을 실행할 수 있지만 크론 스크립트를 변경하여 잠금 메커니즘을 구현하는 약간의 논리로 시작하므로 한 서버 만 실제로 조치를 취하고 다른 서버는 건너 뜁니다. 나는 잠재적으로 버그가 들릴 수 있으므로이 아이디어를 좋아하지 않으며 우리 자신을 굴리는 대신 아마존 모범 사례를 사용하는 것을 선호합니다.
  • 작업이 어딘가에 일정이 잡혀 대기열에 추가 된 다음 웹 서버가 각각 작업자 일 수있는 상황을 상상하고 있습니다. Amazon Simple Workflow Service는 이런 종류의 소리를 정확하게 들지만 현재 그것에 대해 많이 알지 못하므로 구체적인 내용이 도움이 될 것입니다. 크론처럼 단순한 것에 대해 무거운 것 같습니까? 올바른 서비스입니까, 아니면 더 적합한 Amazon 서비스가 있습니까?

업데이트 : 질문 을 한 후 YouTube 에서 Amazon Simple Workflow Service 웨비나를 보았고 34:40 ( http://www.youtube.com/watch?v=lBUQiek8Jqk#t=34m40s ) 을 보았습니다 . 샘플 응용 프로그램으로 cron 작업을 언급하는 슬라이드. Amazon 의 설명서 페이지 " Amazon SWF 용 AWS Flow Framework 샘플 "에서 아마존은 크론 용 샘플 코드가 있다고 말합니다.

... > Cron 작업 이 샘플에서 장기 실행 워크 플로우는 주기적으로 활동을 실행합니다. 실행을 매우 오랜 시간 동안 실행할 수 있도록 새 실행으로 실행을 계속할 수있는 기능이 시연됩니다. ...

Java 용 AWS SDK ( http://aws.amazon.com/sdkforjava/ ) 를 다운로드했으며 어리석은 폴더 레이어 내에 충분히 묻혀 있는지 확인하십시오 aws-java-sdk-1.3.6/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/periodicworkflow. 일부 Java 코드 ( )가 있습니다.

문제는 내가 정직하다면 내 스킬 셋으로 쉽게 소화 할 수있는 것이 아니기 때문에 실제로 도움이되지 않는다는 것입니다. 동일한 샘플이 PHP SDK에서 누락되었으며 프로세스를 진행하는 자습서가없는 것 같습니다. 그래서 기본적으로, 나는 여전히 조언이나 팁을 찾고 있습니다.


이 질문을하기 위해 Amazon Gold 지원에 가입했습니다.

나는 내 동료 중 일부의 빠른 설문 조사를 수행하고 cron에서 비워졌습니다. 그러나 자고 나면 중요한 단계가 잠금으로 제한 될 수 있음을 깨달았습니다. 그래서 "분산 된 크론 작업 잠금"을 찾고 Apache 프로젝트 인 Zookeeper에 대한 참조를 찾았습니다.

http://zookeeper.apache.org/doc/r3.2.2/recipes.html

http://highscalability.com/blog/2010/3/22/7-secrets-to-successfully-scaling-with-scalr-on-amazon-by-se.html

또한 TTL로 잠금을 만드는 방법으로 memcached 또는 유사한 캐싱 메커니즘을 사용하는 것에 대한 참조를 보았습니다. 이런 식으로 TTL이 300 초인 플래그를 설정하면 다른 크론 작업자가 작업을 실행하지 않습니다. TTL이 만료되면 잠금이 자동으로 해제됩니다. 이것은 개념적으로 어제 논의한 SQS 옵션과 매우 유사합니다.

또한보십시오; 구글의 통통한 http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en//archive/chubby-osdi06.pdf

이것이 도움이되는지 알려 주시면 언제든지 문의하십시오. 우리는 초보자와 숙련 된 개발자 모두에게 서비스가 복잡하고 어려울 수 있음을 잘 알고 있습니다. 우리는 항상 건축과 모범 사례 조언을 기꺼이 제공합니다.

친애하는,

Ronan G. Amazon 웹 서비스


나는이 비디오가 당신의 정확한 질문에 대답한다고 생각합니다-cronjobs aws way (확장 성 및 내결함성) :

Amazon Simple Workflow와 함께 클라우드에서 Cron 사용

비디오는 cronjob을 구현하는 특정 사용 사례를 사용하여 SWF 서비스에 대해 설명합니다 .

crontab에서 직접 오는 경우 솔루션의 상대적 복잡성은 삼키기가 어려울 수 있습니다. 마지막에는 복잡성이 더해주는 것이 무엇인지 이해하는 데 도움이되는 사례 연구가 있습니다. 기존 crontab 솔루션에서 마이그레이션해야하는지 여부를 결정하기 위해 사례 연구를보고 확장 성 및 내결함성 요구 사항을 고려하는 것이 좋습니다.


cronjob에 SQS를 사용할 때는 "한 시스템에서만 하나의 작업 만 볼 수 있음"을 보장하지 않으므로주의하십시오. 그들은 "적어도 하나"가 메시지를받을 것을 보증합니다.

보낸 사람 : http://aws.amazon.com/sqs/faqs/#How_many_times_will_I_receive_each_message

Q : 각 메시지는 몇 번이나 받습니까?

Amazon SQS는 대기열에있는 모든 메시지를 "한 번 이상"전달하도록 설계되었습니다. 대부분의 경우 각 메시지가 응용 프로그램에 정확히 한 번만 전달되지만 메시지를 두 번 이상 처리해도 오류나 불일치가 발생하지 않도록 시스템을 설계해야합니다.

지금까지 Gearman Job Server 인스턴스가 설치된 인스턴스가 하나 인 솔루션 ( http://gearman.org/)에 대해 생각할 수 있습니다 . 동일한 머신에서 백그라운드에서 cronjob 태스크를 실행하도록 명령을 생성하는 cron 작업을 구성합니다. 그런 다음 웹 서버 (작업자) 중 하나가이 작업을 실행하기 시작하여 하나만 수행하도록합니다. 직원 수는 중요하지 않습니다 (특히 자동 스케일링을 사용하는 경우).

이 솔루션의 문제점은 다음과 같습니다.

  • Gearman server is single point of failure, unless you configure it with distributed storage, for example using memcached or some database
  • Then using multiple Gearman servers you have to select one that creates task via cronjob, so again we are back to the same problem. But if you can live with this kind of single point of failure using Gearman looks like quite good solution. Especially that you don't need big instance for that (micro instance in our case is enough).

Amazon has just released new features for Elastic Beanstalk. From the docs:

AWS Elastic Beanstalk supports periodic tasks for worker environment
tiers in environments running a predefined configuration with a solution stack that contains "v1.2.0" in the container name. "

You can now create an environment containing a cron.yaml file that configures scheduling tasks:

version: 1
cron:
- name: "backup-job"          # required - unique across all entries in this file
  url: "/backup"              # required - does not need to be unique
  schedule: "0 */12 * * *"    # required - does not need to be unique
- name: "audit"
  url: "/audit"
   schedule: "0 23 * * *"

I would imagine the insurance of running it only once in an autoscaled environment is utilized via the message queue (SQS). When the cron daemon triggers an event it puts that call in the SQS queue and the message in the queue is only evaluated once. The docs say that execution might be delayed if SQS has many messages to process.


I came across this question for the third time now and thought I'd chip in. We've had this dilemma for a while now. I still really feel AWS is missing a feature here.

In our case, after looking at the possible solutions, we decided we had two options:

  • Set up a cronjob server which runs the jobs that should only be run once at a time, auto scale it and make sure it's replaced when certain CloudWatch stats aren't what they should be. We use cloud-init scripts to get the cronjobs running. Of course, this comes with a downtime, leading to missed cronjobs (when running certain tasks every minute, like we do).
  • Use the logic that rcron uses. Of course, the magic is not really in rcron itself, it's in the logic you use to detect a failing node (we use keepalived here) and "upgrade" another node to master.

We decided to go with the second option, simply because it's brilliantly fast and we already had experience with webservers running these cronjobs (in our pre-AWS era).

Of course, this solution is meant specifically for replacing the traditional one-node cronjob approach, where timing is the deciding factor (e.g. "I want job A to run once daily at 5 AM", or like in our case "I want job B to run once every minute"). If you use cronjobs to trigger batch-processing logic, you should really take a look at SQS. There's no active-passive dilemma, meaning you can use a single server or an entire workforce to process your queue. I'd also suggest looking at SWF for scaling your workforce (although auto scaling might be able to do the trick as well in most cases).

Depending on another third party was something we wanted to avoid.


On 12/Feb/16 Amazon blogged about Scheduling SSH jobs using AWS Lambda. I think this answers the question.


The "Amazon" way is to be distributed, meaning bulky crons should be split into many smaller jobs and handed to the right machines. Using SQS to glue it together ensures each job is seen by only one machine. It also tolerates failure since the queues will buffer until a machine spins back up.

Also consider whether you really need to 'batch' these operations. What happens if one night's updates are considerably larger than expected? Even with dynamic resourcing, your processing could be delayed waiting for enough machines to spin up. Instead, store your data in SDB, notify machines of updates via SQS, and create your RSS feed on the fly (with caching).

Batch jobs are from a time when processing resources were limited and 'live' services took precedence. In the cloud, this is not the case.


If you already have a Redis service up, this looks like a good solution:

https://github.com/kvz/cronlock

Read more: http://kvz.io/blog/2012/12/31/lock-your-cronjobs/


Why would you build your own? Why not use something like Quartz (with Clustered Scheduling). See documentation.

http://quartz-scheduler.org/documentation/quartz-2.x/configuration/ConfigJDBCJobStoreClustering


What we do is we have one particular server that is part of our web application cluster behind an ELB also assigned a specific DNS name so that we can run the jobs on that one specific server. This also has the benefit that if that job causes that server to slow down, the ELB will remove it from the cluster and then return it once the job is over and it gets healthy again.

Works like a champ.


If you're willing to use a non-AWS service, then you might check out Microsoft Azure. Azure offers a great job scheduler.


Since no one has mentioned CloudWatch Event, I'd say that it's the AWS way of doing cron jobs. It can run many actions, such as Lambda function, ECS task.

참고URL : https://stackoverflow.com/questions/10061843/how-to-convert-linux-cron-jobs-to-the-amazon-way

반응형