Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 640 lines (577 sloc) 22.252 kb
99ab53c @CloudMarc Initial Commit
CloudMarc authored
1 <?php
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
2 /**
3 * PHP client for IronWorker
4 * IronWorker is a massively scalable background processing system.
5 *
6 * @link https://github.com/iron-io/iron_worker_php
7 * @link http://www.iron.io/
68eaa13 @thousandsofthem docs -> dev
thousandsofthem authored
8 * @link http://dev.iron.io/
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
9 * @version 1.3.3
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
10 * @package IronWorkerPHP
11 * @copyright Feel free to copy, steal, take credit for, or whatever you feel like doing with this code. ;)
12 */
13
14 /**
9a15218 @thousandsofthem Common functional moved to iron_core_php
thousandsofthem authored
15 * IronWorker internal exceptions representation
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
16 */
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
17 class IronWorker_Exception extends Exception{
18
19 }
20
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
21 /**
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
22 * Class that wraps IronWorker API calls.
23 */
9a15218 @thousandsofthem Common functional moved to iron_core_php
thousandsofthem authored
24 class IronWorker extends IronCore{
99ab53c @CloudMarc Initial Commit
CloudMarc authored
25
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
26 protected $client_version = '1.3.3';
9a15218 @thousandsofthem Common functional moved to iron_core_php
thousandsofthem authored
27 protected $client_name = 'iron_worker_php';
28 protected $product_name = 'iron_worker';
29 protected $default_values = array(
6c007d3 @thousandsofthem 5.2 Compability restored. Warnings removed.
thousandsofthem authored
30 'protocol' => 'https',
3b70cee @thousandsofthem Make all params except token optional.
thousandsofthem authored
31 'host' => 'worker-aws-us-east-1.iron.io',
6c007d3 @thousandsofthem 5.2 Compability restored. Warnings removed.
thousandsofthem authored
32 'port' => '443',
3b70cee @thousandsofthem Make all params except token optional.
thousandsofthem authored
33 'api_version' => '2',
34 );
6617afd @thousandsofthem Initial release.
thousandsofthem authored
35
36 /**
ddebad4 @thousandsofthem load configuration data from different sources.
thousandsofthem authored
37 * @param string|array|null $config_file_or_options
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
38 * Array of options or name of config file.
39 * Fields in options array or in config:
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
40 *
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
41 * Required:
c7e9e04 @thousandsofthem New validations, comments. Fixing tests.
thousandsofthem authored
42 * - token
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
43 * - project_id
3ebd66d @thousandsofthem SimpleWorker => IronWorker. Examples moved to separate directory.
thousandsofthem authored
44 * Optional:
c7e9e04 @thousandsofthem New validations, comments. Fixing tests.
thousandsofthem authored
45 * - protocol
46 * - host
47 * - port
48 * - api_version
ddebad4 @thousandsofthem load configuration data from different sources.
thousandsofthem authored
49 *
50 * Configuration data will be searched in this locations:
51 * 1. passed to class constructor
52 * 2a. config file iron.ini in current directory
53 * 2b. config file iron.json in current directory
54 * 3a. environment variables IRON_WORKER_TOKEN and others
55 * 3b. environment variables IRON_TOKEN and others
56 * 4a. config file ~/.iron.ini in user home dir
57 * 4b. config file ~/.iron.json in user home dir
58 *
6617afd @thousandsofthem Initial release.
thousandsofthem authored
59 */
ddebad4 @thousandsofthem load configuration data from different sources.
thousandsofthem authored
60 function __construct($config_file_or_options = null){
61 $this->getConfigData($config_file_or_options);
62 $this->url = "{$this->protocol}://{$this->host}:{$this->port}/{$this->api_version}/";
99ab53c @CloudMarc Initial Commit
CloudMarc authored
63 }
64
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
65 /**
aa2991e @thousandsofthem New upload() method
thousandsofthem authored
66 * Zips and uploads your code
67 *
68 * Shortcut for zipDirectory() + postCode()
69 *
70 * @param string $directory Directory with worker files
71 * @param string $run_filename This file will be launched as worker
72 * @param string $code_name Referenceable (unique) name for your worker
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
73 * @param array $options Optional parameters:
74 * - "max_concurrency" The maximum number of tasks that should be run in parallel.
75 * - "retries" The number of auto-retries of failed task.
76 * - "retries_delay" Delay in seconds between retries.
aa2991e @thousandsofthem New upload() method
thousandsofthem authored
77 * @return bool Result of operation
78 * @throws Exception
79 */
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
80 public function upload($directory, $run_filename, $code_name, $options = array()){
aa2991e @thousandsofthem New upload() method
thousandsofthem authored
81 $temp_file = tempnam(sys_get_temp_dir(), 'iron_worker_php');
82 if (!self::zipDirectory($directory, $temp_file, true)){
83 unlink($temp_file);
84 return false;
85 }
86 try{
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
87 $this->postCode($run_filename, $temp_file, $code_name, $options);
aa2991e @thousandsofthem New upload() method
thousandsofthem authored
88 }catch(Exception $e){
89 unlink($temp_file);
90 throw $e;
91 }
7c1549f @thousandsofthem fix tests; fix minor error;bersion bump
thousandsofthem authored
92 return true;
aa2991e @thousandsofthem New upload() method
thousandsofthem authored
93 }
94
95 /**
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
96 * Creates a zip archieve from array of file names
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
97 *
98 * Example:
99 * <code>
100 * IronWorker::createZip(dirname(__FILE__), array('HelloWorld.php'), 'worker.zip', true);
101 * </code>
102 *
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
103 * @static
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
104 * @param string $base_dir Full path to directory which contain files
105 * @param array $files File names, path (both passesed and stored) is relative to $base_dir.
106 * Examples: 'worker.php','lib/file.php'
107 * @param string $destination Zip file name.
108 * @param bool $overwrite Overwite existing file or not.
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
109 * @return bool
110 */
111 public static function createZip($base_dir, $files = array(), $destination, $overwrite = false) {
99ab53c @CloudMarc Initial Commit
CloudMarc authored
112 //if the zip file already exists and overwrite is false, return false
113 if(file_exists($destination) && !$overwrite) { return false; }
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
114 if (!empty($base_dir)) $base_dir = rtrim($base_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
99ab53c @CloudMarc Initial Commit
CloudMarc authored
115 //vars
116 $valid_files = array();
117 //if files were passed in...
118 if(is_array($files)) {
119 //cycle through each file
120 foreach($files as $file) {
121 //make sure the file exists
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
122 if(file_exists($base_dir.$file)) {
99ab53c @CloudMarc Initial Commit
CloudMarc authored
123 $valid_files[] = $file;
124 }
125 }
126 }
127 if(count($valid_files)) {
128 $zip = new ZipArchive();
129 if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
130 return false;
131 }
132 foreach($valid_files as $file) {
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
133 $zip->addFile($base_dir.$file, $file);
99ab53c @CloudMarc Initial Commit
CloudMarc authored
134 }
135 $zip->close();
136 return file_exists($destination);
6617afd @thousandsofthem Initial release.
thousandsofthem authored
137 }else{
99ab53c @CloudMarc Initial Commit
CloudMarc authored
138 return false;
139 }
140 }
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
141
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
142 /**
143 * Creates a zip archieve with all files and folders inside specific directory.
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
144 *
145 * Example:
146 * <code>
147 * IronWorker::zipDirectory(dirname(__FILE__)."/worker/", 'worker.zip', true);
148 * </code>
149 *
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
150 * @static
151 * @param string $directory
152 * @param string $destination
153 * @param bool $overwrite
154 * @return bool
155 */
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
156 public static function zipDirectory($directory, $destination, $overwrite = false){
157 if (!file_exists($directory) || !is_dir($directory)) return false;
158 $directory = rtrim($directory, DIRECTORY_SEPARATOR);
159
160 $files = self::fileNamesRecursive($directory);
161
162 if (empty($files)) return false;
163
164 return self::createZip($directory, $files, $destination, $overwrite);
165 }
166
6617afd @thousandsofthem Initial release.
thousandsofthem authored
167 public function setProjectId($project_id) {
168 if (!empty($project_id)){
99ab53c @CloudMarc Initial Commit
CloudMarc authored
169 $this->project_id = $project_id;
170 }
c7e9e04 @thousandsofthem New validations, comments. Fixing tests.
thousandsofthem authored
171 if (empty($this->project_id)){
172 throw new InvalidArgumentException("Please set project_id");
173 }
99ab53c @CloudMarc Initial Commit
CloudMarc authored
174 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
175
176 public function getProjects(){
99ab53c @CloudMarc Initial Commit
CloudMarc authored
177 $this->setJsonHeaders();
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
178 $projects = self::json_decode($this->apiCall(self::GET, 'projects'));
99ab53c @CloudMarc Initial Commit
CloudMarc authored
179 return $projects->projects;
180 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
181
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
182 public function getTasks($page = 0, $per_page = 30){
6617afd @thousandsofthem Initial release.
thousandsofthem authored
183 $url = "projects/{$this->project_id}/tasks";
99ab53c @CloudMarc Initial Commit
CloudMarc authored
184 $this->setJsonHeaders();
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
185 $params = array(
186 'page' => $page,
187 'per_page' => $per_page
188 );
189 $task = self::json_decode($this->apiCall(self::GET, $url, $params));
6617afd @thousandsofthem Initial release.
thousandsofthem authored
190 return $task->tasks;
99ab53c @CloudMarc Initial Commit
CloudMarc authored
191 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
192
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
193 public function getProjectDetails(){
99ab53c @CloudMarc Initial Commit
CloudMarc authored
194 $this->setJsonHeaders();
6617afd @thousandsofthem Initial release.
thousandsofthem authored
195 $url = "projects/{$this->project_id}";
99ab53c @CloudMarc Initial Commit
CloudMarc authored
196 return json_decode($this->apiCall(self::GET, $url));
197 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
198
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
199 public function getCodes($page = 0, $per_page = 30){
6617afd @thousandsofthem Initial release.
thousandsofthem authored
200 $url = "projects/{$this->project_id}/codes";
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
201 $this->setJsonHeaders();
202 $params = array(
203 'page' => $page,
204 'per_page' => $per_page
205 );
206 $codes = self::json_decode($this->apiCall(self::GET, $url, $params));
99ab53c @CloudMarc Initial Commit
CloudMarc authored
207 return $codes->codes;
208 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
209
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
210 public function getCodeDetails($code_id){
c7e9e04 @thousandsofthem New validations, comments. Fixing tests.
thousandsofthem authored
211 if (empty($code_id)){
212 throw new InvalidArgumentException("Please set code_id");
213 }
99ab53c @CloudMarc Initial Commit
CloudMarc authored
214 $this->setJsonHeaders();
6617afd @thousandsofthem Initial release.
thousandsofthem authored
215 $url = "projects/{$this->project_id}/codes/$code_id";
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
216 return self::json_decode($this->apiCall(self::GET, $url));
99ab53c @CloudMarc Initial Commit
CloudMarc authored
217 }
218
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
219 /**
220 * Uploads your code package
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
221 *
222 * @param string $filename This file will be launched as worker
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
223 * @param string $zipFilename zip file containing code to execute
224 * @param string $name referenceable (unique) name for your worker
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
225 * @param array $options Optional parameters:
226 * - "max_concurrency" The maximum number of tasks that should be run in parallel.
227 * - "retries" The number of auto-retries of failed task.
228 * - "retries_delay" Delay in seconds between retries.
390db9d @thousandsofthem PDO example for client php class. PHPdoc comments.
thousandsofthem authored
229 * @return mixed
230 */
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
231 public function postCode($filename, $zipFilename, $name, $options = array()){
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
232
233 // Add IronWorker functions to the uploaded worker
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
234 $this->addRunnerToArchive($zipFilename, $filename);
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
235
99ab53c @CloudMarc Initial Commit
CloudMarc authored
236 $this->setPostHeaders();
237 $ts = time();
238 $runtime_type = $this->runtimeFileType($filename);
6617afd @thousandsofthem Initial release.
thousandsofthem authored
239 $sendingData = array(
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
240 "code_name" => $name,
241 "name" => $name,
6617afd @thousandsofthem Initial release.
thousandsofthem authored
242 "standalone" => True,
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
243 "runtime" => $runtime_type,
244 "file_name" => "runner.php",
245 "version" => $this->version,
246 "timestamp" => $ts,
247 "oauth" => $this->token,
6617afd @thousandsofthem Initial release.
thousandsofthem authored
248 "class_name" => $name,
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
249 "options" => array(),
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
250 "access_key" => $name
251 );
7375db3 @thousandsofthem added max_concurrency, retries, retries_delay to code uploading; vers…
thousandsofthem authored
252 $sendingData = array_merge($sendingData, $options);
934a69f @thousandsofthem Upload code: replaced file_get_contents with curl.
thousandsofthem authored
253 $url = "projects/{$this->project_id}/codes";
254 $post = array(
255 "data" => json_encode($sendingData),
256 "file"=>"@".$zipFilename,
257 );
258 $response = $this->apiCall(self::POST, $url, array(), $post);
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
259 return self::json_decode($response);
99ab53c @CloudMarc Initial Commit
CloudMarc authored
260 }
261
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
262 public function deleteCode($code_id){
6617afd @thousandsofthem Initial release.
thousandsofthem authored
263 $url = "projects/{$this->project_id}/codes/$code_id";
99ab53c @CloudMarc Initial Commit
CloudMarc authored
264 return $this->apiCall(self::DELETE, $url);
265 }
266
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
267 public function deleteSchedule($schedule_id){
eb336f4 @thousandsofthem API updated.
thousandsofthem authored
268 $url = "projects/{$this->project_id}/schedules/$schedule_id/cancel";
2c02c0d @thousandsofthem Several new API calls.
thousandsofthem authored
269
270 $request = array(
271 'schedule_id' => $schedule_id
272 );
273
9a15218 @thousandsofthem Common functional moved to iron_core_php
thousandsofthem authored
274 return self::json_decode($this->apiCall(self::POST, $url, $request));
99ab53c @CloudMarc Initial Commit
CloudMarc authored
275 }
276
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
277 /**
278 * Get information about all schedules for project
279 *
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
280 * @param int $page
281 * @param int $per_page
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
282 * @return mixed
283 */
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
284 public function getSchedules($page = 0, $per_page = 30){
6617afd @thousandsofthem Initial release.
thousandsofthem authored
285 $url = "projects/{$this->project_id}/schedules";
0be32a1 @thousandsofthem Added page and per_page options
thousandsofthem authored
286 $this->setJsonHeaders();
287 $params = array(
288 'page' => $page,
289 'per_page' => $per_page
290 );
291 $schedules = self::json_decode($this->apiCall(self::GET, $url, $params));
99ab53c @CloudMarc Initial Commit
CloudMarc authored
292 return $schedules->schedules;
293 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
294
295 /**
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
296 * Get information about schedule
297 *
298 * @param string $schedule_id Schedule ID
299 * @return mixed
300 * @throws InvalidArgumentException
301 */
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
302 public function getSchedule($schedule_id){
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
303 if (empty($schedule_id)){
304 throw new InvalidArgumentException("Please set schedule_id");
305 }
306 $this->setJsonHeaders();
307 $url = "projects/{$this->project_id}/schedules/$schedule_id";
308
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
309 return self::json_decode($this->apiCall(self::GET, $url));
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
310 }
311
312 /**
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
313 * Schedules task
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
314 *
315 * @param string $name Package name
316 * @param array $payload Payload for task
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
317 * @param int $delay Delay in seconds
318 * @return string Created Schedule id
6617afd @thousandsofthem Initial release.
thousandsofthem authored
319 */
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
320 public function postScheduleSimple($name, $payload = array(), $delay = 1){
321 return $this->postSchedule($name, array('delay' => $delay), $payload);
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
322 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
323
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
324 /**
c25744e @thousandsofthem New api call getSchedule(). Humanized package names for examples.
thousandsofthem authored
325 * Schedules task
326 *
b0f9150 @develop7 made IronWorker::postScheduleAdvanced() accept DateTime instances as …
develop7 authored
327 * @param string $name Package name
328 * @param array $payload Payload for task
329 * @param int|DateTime $start_at Time of first run in unix timestamp format or as DateTime instance. Example: time()+2*60
330 * @param int $run_every Time in seconds between runs. If omitted, task will only run once.
331 * @param int|DateTime $end_at Time tasks will stop being enqueued in unix timestamp or as DateTime instance format.
332 * @param int $run_times Number of times to run task.
333 * @param int $priority Priority queue to run the job in (0, 1, 2). p0 is default.
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
334 * @return string Created Schedule id
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
335 */
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
336 public function postScheduleAdvanced($name, $payload = array(), $start_at, $run_every = null, $end_at = null, $run_times = null, $priority = null){
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
337 $options = array();
7ac14f1 @thousandsofthem Allow pass $payload to schedule. Time usage simplified for schedule*.
thousandsofthem authored
338 $options['start_at'] = self::dateRfc3339($start_at);
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
339 if (!empty($run_every)) $options['run_every'] = $run_every;
7ac14f1 @thousandsofthem Allow pass $payload to schedule. Time usage simplified for schedule*.
thousandsofthem authored
340 if (!empty($end_at)) $options['end_at'] = self::dateRfc3339($end_at);
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
341 if (!empty($run_times)) $options['run_times'] = $run_times;
342 if (!empty($priority)) $options['priority'] = $priority;
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
343 return $this->postSchedule($name, $options, $payload);
99ab53c @CloudMarc Initial Commit
CloudMarc authored
344 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
345
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
346 /**
347 * Queues already uploaded worker
348 *
349 * @param string $name Package name
ff09f6f @thousandsofthem Added new options "priority", "timeout","delay" for postTask()
thousandsofthem authored
350 * @param array $payload Payload for task
351 * @param array $options Optional parameters:
352 * - "priority" priority queue to run the job in (0, 1, 2). 0 is default.
353 * - "timeout" maximum runtime of your task in seconds. Maximum time is 3600 seconds (60 minutes). Default is 3600 seconds (60 minutes).
354 * - "delay" delay before actually queueing the task in seconds. Default is 0 seconds.
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
355 * @return string Created Task ID
356 */
ff09f6f @thousandsofthem Added new options "priority", "timeout","delay" for postTask()
thousandsofthem authored
357 public function postTask($name, $payload = array(), $options = array()){
6617afd @thousandsofthem Initial release.
thousandsofthem authored
358 $url = "projects/{$this->project_id}/tasks";
359
360 $request = array(
361 'tasks' => array(
362 array(
363 "name" => $name,
364 "code_name" => $name,
67eaa54 @thousandsofthem Zip packer fix. Directory referencing fix. Payload for worker.
thousandsofthem authored
365 'payload' => json_encode($payload),
6617afd @thousandsofthem Initial release.
thousandsofthem authored
366 )
367 )
368 );
369
ff09f6f @thousandsofthem Added new options "priority", "timeout","delay" for postTask()
thousandsofthem authored
370 foreach ($options as $k => $v){
371 $request['tasks'][0][$k] = $v;
372 }
373
6617afd @thousandsofthem Initial release.
thousandsofthem authored
374 $this->setCommonHeaders();
375 $res = $this->apiCall(self::POST, $url, $request);
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
376 $tasks = self::json_decode($res);
fd32265 @thousandsofthem Code cleanup, almost all methods work as expected.
thousandsofthem authored
377 return $tasks->tasks[0]->id;
99ab53c @CloudMarc Initial Commit
CloudMarc authored
378 }
6617afd @thousandsofthem Initial release.
thousandsofthem authored
379
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
380 public function getLog($task_id){
c7e9e04 @thousandsofthem New validations, comments. Fixing tests.
thousandsofthem authored
381 if (empty($task_id)){
382 throw new InvalidArgumentException("Please set task_id");
383 }
99ab53c @CloudMarc Initial Commit
CloudMarc authored
384 $this->setJsonHeaders();
cbd59af @thousandsofthem Fixing typos.
thousandsofthem authored
385 $url = "projects/{$this->project_id}/tasks/$task_id/log";
99ab53c @CloudMarc Initial Commit
CloudMarc authored
386 $this->headers['Accept'] = "text/plain";
387 unset($this->headers['Content-Type']);
6617afd @thousandsofthem Initial release.
thousandsofthem authored
388 return $this->apiCall(self::GET, $url);
8192308 @thousandsofthem Checking status for task.
thousandsofthem authored
389 }
390
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
391 public function getTaskDetails($task_id){
8192308 @thousandsofthem Checking status for task.
thousandsofthem authored
392 if (empty($task_id)){
393 throw new InvalidArgumentException("Please set task_id");
394 }
395 $this->setJsonHeaders();
396 $url = "projects/{$this->project_id}/tasks/$task_id";
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
397 return self::json_decode($this->apiCall(self::GET, $url));
99ab53c @CloudMarc Initial Commit
CloudMarc authored
398 }
399
0e65e49 @thousandsofthem Old api calls removed.
thousandsofthem authored
400 /**
401 * Cancels task.
402 *
403 * @param string $task_id Task ID
404 * @return mixed
405 * @throws InvalidArgumentException
406 */
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
407 public function cancelTask($task_id){
4813b55 @thousandsofthem Minor improvements.
thousandsofthem authored
408 if (empty($task_id)){
409 throw new InvalidArgumentException("Please set task_id");
410 }
cbd59af @thousandsofthem Fixing typos.
thousandsofthem authored
411 $url = "projects/{$this->project_id}/tasks/$task_id/cancel";
2c02c0d @thousandsofthem Several new API calls.
thousandsofthem authored
412 $request = array();
413
414 $this->setCommonHeaders();
415 $res = $this->apiCall(self::POST, $url, $request);
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
416 return self::json_decode($res);
2c02c0d @thousandsofthem Several new API calls.
thousandsofthem authored
417 }
418
0e65e49 @thousandsofthem Old api calls removed.
thousandsofthem authored
419 /**
420 * Cancels task.
421 *
422 * @param string $task_id Task ID
423 * @return mixed
424 * @throws InvalidArgumentException
425 */
426 public function deleteTask($task_id){
427 return $this->cancelTask($task_id);
428 }
429
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
430 public function setTaskProgress($task_id, $percent, $msg = ''){
4813b55 @thousandsofthem Minor improvements.
thousandsofthem authored
431 if (empty($task_id)){
432 throw new InvalidArgumentException("Please set task_id");
433 }
cbd59af @thousandsofthem Fixing typos.
thousandsofthem authored
434 $url = "projects/{$this->project_id}/tasks/$task_id/progress";
2c02c0d @thousandsofthem Several new API calls.
thousandsofthem authored
435 $request = array(
436 'percent' => $percent,
437 'msg' => $msg
438 );
439
440 $this->setCommonHeaders();
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
441 return self::json_decode($this->apiCall(self::POST, $url, $request));
2c02c0d @thousandsofthem Several new API calls.
thousandsofthem authored
442 }
828b5b4 @thousandsofthem new waitFor() method
thousandsofthem authored
443 /**
444 * Wait while the task specified by task_id executes
445 *
446 * @param string $task_id Task ID
447 * @param int $sleep Delay between API invocations in seconds
448 * @param int $max_wait_time Maximum waiting time in seconds, 0 for infinity
449 * @return mixed $details Task details or false
450 */
451 public function waitFor($task_id, $sleep = 5, $max_wait_time = 0){
452 while(1){
453 $details = $this->getTaskDetails($task_id);
454
455 if ($details->status != 'queued' && $details->status != 'running'){
456 return $details;
457 }
458 if ($max_wait_time > 0){
459 $max_wait_time -= $sleep;
460 if ($max_wait_time <= 0) return false;
461 }
462
463 sleep($sleep);
464 }
465 return false;
466 }
2c02c0d @thousandsofthem Several new API calls.
thousandsofthem authored
467
6617afd @thousandsofthem Initial release.
thousandsofthem authored
468 /* PRIVATE FUNCTIONS */
469
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
470 /**
471 *
472 * @param string $name
67eaa54 @thousandsofthem Zip packer fix. Directory referencing fix. Payload for worker.
thousandsofthem authored
473 * @param array $options options contain:
474 * start_at OR delay — required - start_at is time of first run. Delay is number of seconds to wait before starting.
475 * run_every — optional - Time in seconds between runs. If omitted, task will only run once.
476 * end_at — optional - Time tasks will stop being enqueued. (Should be a Time or DateTime object.)
477 * run_times — optional - Number of times to run task. For example, if run_times: is 5, the task will run 5 times.
478 * priority — optional - Priority queue to run the job in (0, 1, 2). p0 is default. Run at higher priorities to reduce time jobs may spend in the queue once they come off schedule. Same as priority when queuing up a task.
479 * @param array $payload
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
480 * @return mixed
481 */
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
482 private function postSchedule($name, $options, $payload = array()){
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
483 $url = "projects/{$this->project_id}/schedules";
484 $shedule = array(
485 'name' => $name,
486 'code_name' => $name,
67eaa54 @thousandsofthem Zip packer fix. Directory referencing fix. Payload for worker.
thousandsofthem authored
487 'payload' => json_encode($payload),
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
488 );
489 $request = array(
490 'schedules' => array(
491 array_merge($shedule, $options)
492 )
493 );
494
495 $this->setCommonHeaders();
496 $res = $this->apiCall(self::POST, $url, $request);
55c09d8 @thousandsofthem Revamp using $project_id. Json exception handling.
thousandsofthem authored
497 $shedules = self::json_decode($res);
adf5ef7 @thousandsofthem Support more scheduling variants.
thousandsofthem authored
498 return $shedules->schedules[0]->id;
499 }
500
6617afd @thousandsofthem Initial release.
thousandsofthem authored
501 private function runtimeFileType($name) {
502 if(empty($name)){
503 return false;
504 }
505 $explodedName= explode(".", $name);
506 switch ($explodedName[(count($explodedName)-1)]) {
507 case "php":
508 return "php";
509 case "rb":
510 return "ruby";
511 case "py":
512 return "python";
513 case "javascript":
514 return "javascript";
515 default:
516 return "no_type_found";
517 }
518 }
519
520 private function getFileContent($filename){
4813b55 @thousandsofthem Minor improvements.
thousandsofthem authored
521 return file_get_contents($filename);
6617afd @thousandsofthem Initial release.
thousandsofthem authored
522 }
523
524 private function setJsonHeaders(){
525 $this->setCommonHeaders();
526 }
527
528 private function setPostHeaders(){
529 $this->setCommonHeaders();
530 $this->headers['Content-Type'] ='multipart/form-data';
531 }
532
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
533 private static function fileNamesRecursive($dir, $base_dir = ''){
534 $dir .= DIRECTORY_SEPARATOR;
535 $files = scandir($dir);
536 $names = array();
537
538 foreach($files as $name){
539 if ($name == '.' || $name == '..' || $name == '.svn') continue;
540 if (is_dir($dir.$name)){
67eaa54 @thousandsofthem Zip packer fix. Directory referencing fix. Payload for worker.
thousandsofthem authored
541 $inner_names = self::fileNamesRecursive($dir.$name, $base_dir.$name.'/');
35794ee @thousandsofthem ZipDirectory feature. PostToTwitter example.
thousandsofthem authored
542 foreach ($inner_names as $iname){
543 $names[] = $iname;
544 }
545 }else{
546 $names[] = $base_dir.$name;
547 }
548 }
549 return $names;
550 }
ba8d418 @thousandsofthem Documentation for IronWorker.class.
thousandsofthem authored
551
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
552
553 /**
554 * Contain php code that adds to worker before upload
555 *
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
556 * @param string $worker_file_name
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
557 * @return string
558 */
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
559 private function workerHeader($worker_file_name){
30867ae @iced support for <php-5.3
iced authored
560 $header = <<<EOL
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
561 <?php
562 /*IRON_WORKER_HEADER*/
563 function getArgs(){
30867ae @iced support for <php-5.3
iced authored
564 global \$argv;
565 \$args = array('task_id' => null, 'dir' => null, 'payload' => array());
566 foreach(\$argv as \$k => \$v){
567 if (empty(\$argv[\$k+1])) continue;
f2d0c13 @thousandsofthem php 5.2 support
thousandsofthem authored
568 if (\$v == '-id') \$args['task_id'] = \$argv[\$k+1];
569 if (\$v == '-d') \$args['dir'] = \$argv[\$k+1];
30867ae @iced support for <php-5.3
iced authored
570 if (\$v == '-payload' && file_exists(\$argv[\$k+1])){
1bc92c5 @thousandsofthem allow non-json payloads
thousandsofthem authored
571 \$args['payload'] = file_get_contents(\$argv[\$k + 1]);
572 \$parsed_payload = json_decode(\$args['payload']);
573 if (\$parsed_payload != null) {
574 \$args['payload'] = \$parsed_payload;
575 }
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
576 }
577 }
30867ae @iced support for <php-5.3
iced authored
578 return \$args;
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
579 }
580
581 function getPayload(){
30867ae @iced support for <php-5.3
iced authored
582 \$args = getArgs();
583 return \$args['payload'];
ed67e6e @thousandsofthem New helper for worker: setProgress()
thousandsofthem authored
584 }
585
30867ae @iced support for <php-5.3
iced authored
586 function setProgress(\$percent, \$msg = ''){
587 \$args = getArgs();
588 \$task_id = \$args['task_id'];
589 \$base_url = '[URL]';
590 \$project_id = '[PROJECT_ID]';
591 \$headers = [HEADERS];
592
593 \$url = "{\$base_url}projects/\$project_id/tasks/\$task_id/progress";
594 \$params = array(
595 'percent' => \$percent,
596 'msg' => \$msg
ed67e6e @thousandsofthem New helper for worker: setProgress()
thousandsofthem authored
597 );
598
30867ae @iced support for <php-5.3
iced authored
599 \$s = curl_init();
600 curl_setopt(\$s, CURLOPT_URL, \$url);
601 curl_setopt(\$s, CURLOPT_POST, true);
602 curl_setopt(\$s, CURLOPT_POSTFIELDS, json_encode(\$params));
603 curl_setopt(\$s, CURLOPT_RETURNTRANSFER, true);
604 curl_setopt(\$s, CURLOPT_HTTPHEADER, \$headers);
605 \$out = curl_exec(\$s);
606 curl_close(\$s);
607 return json_decode(\$out);
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
608 }
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
609 require dirname(__FILE__)."/[SCRIPT]";
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
610 EOL;
ed67e6e @thousandsofthem New helper for worker: setProgress()
thousandsofthem authored
611 $header = str_replace(
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
612 array('[PROJECT_ID]','[URL]','[HEADERS]','[SCRIPT]'),
613 array($this->project_id, $this->url, var_export($this->compiledHeaders(), true), $worker_file_name),
ed67e6e @thousandsofthem New helper for worker: setProgress()
thousandsofthem authored
614 $header
615 );
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
616 return trim($header," \n\r");
617 }
618
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
619 private function addRunnerToArchive($archive, $worker_file_name){
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
620 $zip = new ZipArchive;
178e189 @iced support for php on windows - another try
iced authored
621 if (!$zip->open($archive, ZIPARCHIVE::CREATE) === true) {
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
622 $zip->close();
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
623 throw new IronWorker_Exception("Archive $archive was not found!");
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
624 }
625
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
626 if ($zip->statName($worker_file_name) === false){
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
627 $zip->close();
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
628 throw new IronWorker_Exception("File $worker_file_name in archive $archive was not found!");
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
629 }
630
a2ea2ed @thousandsofthem Introduced runner.php instead of header. Bump version to 1.1.0
thousandsofthem authored
631 if (!$zip->addFromString('runner.php', $this->workerHeader($worker_file_name))){
632 throw new IronWorker_Exception("Adding Runner to the worker failed");
62a08c6 @thousandsofthem Added functions getArgs() and getPayload() to a worker.
thousandsofthem authored
633 }
634
635 $zip->close();
636 return true;
637 }
638
99ab53c @CloudMarc Initial Commit
CloudMarc authored
639 }
Something went wrong with that request. Please try again.