Въвеждане
Аз работя в компания, в която ще свършим много работни места за пакетна обработка на милиони записи на данни всеки ден и аз си мисля напоследък за всички машини, които седят около всеки ден правиш нищо в продължение на няколко часа. Не би ли било добре, ако можем да използваме тези машини, за да уплътнят процесорна мощ на нашите системи? В тази поредица от статии, аз ще разгледаме потенциалните ползи за наемане на офис мрежа с помощта на виртуализирани среди.
В част 1 дадох един преглед на системата и технологията ще се използва, както и обсъдени някои от възможните причини, поради които бихте искали да се създаде мрежа на офис.
Контрол на работата
Ако ще да се работи на работни места, тогава започваш да се нуждаят от някакъв начин да ги управляват. Вашата система за контрол на работата (работата на вашия сървър) трябва да бъдат наистина добре обмислени, преди дори да се опитвате да стартирате офис мрежа. Така че на първо място, какви са задачите, за система за контрол на работата:
- Раздават работни места при поискване от работещите
- Кажете на работници, за какъв тип на работни места да тече
- Проследяване на работни места
- Уверете се, че работните места са се изпълнява само веднъж
- Осигуряване на работа данни на работниците, или поне да им кажа къде да го получите
Системата също така трябва да бъде разширяем, едно решение, че работи за сега в един случай може да бъде удължен, за да стартирате няколко вида работни места, като бизнеса, вижда качества в мрежа разтвор. Например, работни места могат да получат приоритет, повече от един вид работа могат да съществуват (т.е. няколко код базите), в крайна сметка дори може да стартирате няколко различни машини работник, които са оптимизирани за всеки вид работа (въпреки че се движи далеч от "родово работник "идея). Винаги се опитваме да мислим за бъдещето, когато разработват системи, кратко визия план може да доведе до дългосрочен план разочарование и увеличаване на времето за развитие.
Работа на сървъра
Отиваме да имат нужда да контролират нашата работа от някъде, това трябва да бъде единствената система във вашата мрежа, който има постоянен указател на ресурс, е, че едно IP адрес, име на хост, URL (с помощта на вътрешен DNS) и т.н. Това е така, защото работници трябва да знаят къде да търсят работа, работниците трябва да се намери система за контрол на работата (не е система за контрол на работата на работниците).
Работата самия сървър не наистина да има сложна задача (в основната система, така или иначе), той трябва да съхранява списък с работни места, ръка работни места, получават резултати, и впоследствие да ги съхранява за по-късно извличане. Как се определят тези части (като например "ръка работни места") може да бъде основна. Късно на ние можем да разширим системата да включва интерфейс на администрацията, да добавяте, редактирате, изтривате, да спре на работни места, но това е извън това упражнение.
Налице е без видима причина, че работата на вашия сървър не може да бъде една виртуална машина в рамките на основната обработка на сървъра при условие да не се източва твърде много средства от него. Сървъра работа обаче се нуждае от висока надеждност, ако тя отива в петък вечер, ти започваш да губиш целия уикенд на обработка, потенциално ви струва няколко седмици стойността на времето за обработка (в сравнение с основната обработка на сървъра) . Вие може да искате да разгледа пускането на сървър на вашата работа натоварване балансирана среда за висока достъпност.
Basic Setup
The basic setup for our job server will consist of what I'm calling one of my LiMP servers (that is Li nux, m ySql, P HP). The code running on the workers will actually work out what jobs it can run by interacting with with job control system databases. Later on we could create a web service and actually hand out jobs rather than having the workers do the hard work themselves, but for now we'll continue using the KISS principle (Keep it Simple, Stupid!).
So, lets create three mySQL tables to deal with jobs. These will be `jobs`, `jobRecords`, and `jobResults`.
Here I'm using SQL Buddy a great little alternative to phpMyAdmin just because its easier to install on centOS (for others see: 10 Great alternatives to phpMyAdmin )
This table consists of 5 simple fields,
- id: Uniquely identify the job
- name: Could be a client reference, or any number of other identifiers
- Status: You need to know where the job is at, eg
- 0: Not started
- 1: Picked up
- 2: Completed
- started_by: Who's started doing the job? This isn't entirely required but is a nice to have. I'd suggest tracking workers by their IP address on your network
- started_at: When did the worker start the job? By tracking jobs that have not completed within X amount of time we know we need to pick up the job once again and start processing by another worker. Workers could stop processing/go offline for any number of reasons, power failure, crash, network loss, etc.
It is easy how this table could be extended with a few additional fields to allow for statistics tracking, a finish time column to see how long the job took, a counter to see how many workers picked up the job (obviously this needs to tend to 1), job priority, the list can go on and on. In more complex job scenarios it would be possible to specify how much memory the worker would need access to (and therefore only use suitable workers), or even what type of worker would be required.
Lets add a few example jobs:
The next table again is quite simple to understand, these are our job records. They are linked to the main jobs table by a column `jobs_id`. The make up of this table very much depends on the data that you need to supply to your workers, lets make a very simple example where we have four columns:
- id: ID of the record
- name: Person's name
- address: Person's address
- jobs_id: The job ID that this record is linked to
The third and final table consists of a results table, it has much the same make up as our records table, and with the addition of some columns could be part of the records table:
- job_record_id: Link the result to the job table
- result: The result data
…and that's all you need for job control! (albeit at a very basic level) In my case I'm pointed to another table where my data to process was located, but this could just as easily been a file, parameters to run simulation code, you name it.
Selecting a job
As stated previously, the workers will do our job management for us for now, so all we need to really do is find a job that needs processing and get the information. How would we do this? Well pick our job selection criteria and look for jobs, in SQL I did the following:
- Take any jobs that are not marked as complete but from our worker and reset them (substitute __ME__ with an identifier, easiest would be IP address):
UPDATE `jobs` SET `status` = 0 WHERE `status` = 1 AND `started_by` = __ME__;
- Using our job selection criteria, select a job and tell the control system that this worker is dealing with it:
UPDATE `jobs` SET `status` = 1, `started_by` = __ME__, `started_at` = NOW() WHERE `status` = 0 OR
(`status` = 1 AND `started_at` > DATE_SUB(NOW(), INTERVAL X HOUR)) ORDER BY `id` ASC;
By grabbing jobs that haven't returned results in X amount of time we ensure that all jobs are run in the event of a worker crashing or going AWOL.
- Next grab the jobs details followed by the records themselves:
SELECT * FROM `jobs` WHERE `started_by` = __ME__ LIMIT 1;
SELECT * FROM `job_records` WHERE `id` = __JOBID__;
Upon completion of the job we insert our result records and mark the job as complete. Remember as jobs can suspend/resume at any time allow for some robustness in your script. It might be that the task suspends half way through updating the job control system, so checking the number of records in a job and the number of results saved back to the job control system would be a wise move.
In addition, whilst this demonstrates how jobs can be selected and managed from an SQL-query frame you should really be abstracting your job control so that if you decide to switch to using a web service, a file based system, XML , or any other number of systems it will not affect the code above it.
Job Configuration
The next aspect to consider is job size and configuration. By playing with job configuration we can strike an excellent balance between speed, process replication, and reliability. Take a couple of scenarios:
- Jobs take 1 day each to run: This means that your workers need 15 days to process each job (remember 10% of the power for 2/3rds of the time). This is clearly not a wise configuration, your job size is way too big! It would take at least double the time to get a job processed should the initial worker go AWOL (time to pick up that it hasn't returned a result plus reprocessing time). In an ideal you'd have at least one full job easily cleared by the end of each long idle period, that way you keep the jobs ticking over and at worst case a job would take two days to process should the first go missing.
- Jobs take 1 minute to run: This means that your workers take about 15 minutes to run each job. Whilst this may initially seem ideal, you gain additional work processing during lunch time, coffee breaks, meetings, etc this scenario puts strain on other areas of your system and introduces its own problems. For example, firstly your setup/processing time ratio is going to go right down, therefore losing system efficiency. Your network is going to be constantly streaming job information to the various workers frustrating staff who are dong their day to day work. You're also going to put more strain on your job processing server as it has to dish out lots and lots of small pieces of work on a regular basis. Lastly, in this situation if your job server goes down you're going to create a huge back log of uncompleted work whereas bigger jobs could of continued processing blissfully unaware that the job server was experiencing difficulties.
In reality there will be no one ideal configuration for your grid setup, much depends on the available resources, types of job, job turnaround time requirements, network capability, and so on. However some guidelines would be:
- Size jobs so that each worker can get through at least 3-4 jobs in a period of 15 hours (the longest likely idle time period)
- Play with the job size so that setup time becomes fairly insignificant compared to the processing time (bearing in mind the above point).
- If a job doesn't complete in double the amount of time (maybe less) you expect it to complete it assume that its gone AWOL and start processing it with another worker. This means you may have to wait up to three times the normal length of a job for it to complete (possibly longer if the subsequent job fails). You may want to reduce this time, but be careful not to reduce it too much as you may start duplicating processing tasks on a regular basis.
- Jobs should be independent of outside requirements as much as possible. The job server, for example, should only be contacted at the start and end of every job.
- Don't saturate your network, this will have two negative effects, your daytime staff will find using the network frustrating and problems may be experienced with connections timing out a problem that will only get worse as you scale your grid.
- Ensure jobs can run on your workers. If jobs become too memory intensive or disk space intensive jobs will start aborting and the only thing you'll notice is a drop in number of jobs processed with no real reason why.
Submitting Results of a Job
When submitting the results of a job it is important to check that results have not been submitted by another worker, especially if the current worker has been dormant for some time.
When results are submitted ensure that the number of results matches the number of records within the job.
As stated previously, and can not be over emphasised, build fault tolerance into job retrieval and results submission. The workers can (and most likely will) go into suspend mode at the most inconvenient of times and this needs to be catered for. Also once again abstracting away your results submission will help cater for future changes to your job control system much easier to deal with.
Обобщение
In this section we have looked at what a job control server needs to do and how to get a very basic system set up. We discussed how to retrieve a job from the control system and how best to configure jobs to get the most our of your office grid system. To finish, a paragraph or two on submitting results back to the job control server was presented.
- A job control server manages jobs and ensures that all work units are completed
- By abstracting your job select/results submission we can change the technology of the control server without much problems
- Configure your jobs to ensure that they are run quickly and efficiently without putting too much pressure on your network infrastructure, and without duplicating processing tasks on a regular basis.
- Ensure that you build fault tolerance and error checking into your routines, workers can suspend and resume and the most inconvenient of times. Remember to check if results have already been submitted by another worker.
Следващия път
In part 3 we'll create our virtual processing machine and set up our windows machines to become idle-time workers.