How to schedule a jenkins job trough url? - php

I'm implementing a way to trigger jenkins jobs and to schedule them with php in my site. The way I'm doing the "on-the-fly" trigger is by simply calling the url of the job with some parameters (I'm also using Build Token Root Plugin so I can trigger the jobs without authentication).
Example below:
$data = array(
'job' => 'JOB NAME',
'token' => 'job_token',
'parameter1' => 'some parameter',
);
$options = array(
'method' => 'POST',
'data' => drupal_http_build_query($data),
'timeout' => 15,
'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);
drupal_http_request('http://localhost:8080/buildByToken/buildWithParameters', $options);
I can trigger the job with multiple parameters but I need to schedule the build. In jenkins there is this option "Build periodically" but it's not a parameter.
Anyone knows a way to schedule the job trough the url way?
Thanks!

You can add ?delay=300secs to the end of the URL to schedule the job to start in five minutes.
Note that sec and secs are currently the only accepted duration units.

Related

Delete or Stop Scheduled State machines of Step Function

We created step function (WAIT State) to execute schedule task based up on user input time.
We are calling this step up function from PHP code so it will create entry in that state machine and step function (WAIT State) will trigger lambda service automatically when it meets countdown timer.
My requirement is to user to have the option to update the time or cancel event from PHP application. at this scenario i have to update existing scheduled step function event/task time to new time or delete the existing scheduled event and create new scheduled event with latest time.
How can i do with this from PHP application?
The below is my PHP code to create event in AWS step function.
$inputData = '{'.'"invocationTime"'. " : " .'"'.'2022-10-28\T13:15:16\Z.'"'.','.'"userid"'. " : " .'"1233345"'.'}';
$data = array(
//This is the schedule in UTC time.
'input' => $inputData,
'name' => 'Test Charan",
//STATIC
'stateMachineArn' => $awsDataarn //AWS stateMachineArn
);
$inputdataaws = array(
'http' => array(
'method' => 'POST',
'content' => json_encode($data),
'header' => "x-api-key: ".$awsDataapiKey."\r\n".
"Content-Type: application/json\r\n"
)
);
$url = 'https://testcharan.execute-api.us-east-1.amazonaws.com/myapplication/scheduletask'; //AWS endpoint URL
$request = stream_context_create($inputdataaws); // TO create data in AWS statemachine
$result = file_get_contents($url, false, $request); //read the data
$response = json_decode($result); //decode the result
The above code will create the event in AWS step function.
How i can update or delete or abort events/execution those or on Running status?
you can't modify a state machine directly on runtime (on my experiece).
I suggest to
manage the scheduling of the execution by eventbridge (https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-cloudwatch-events-target.html)
create another Lambda that act as "trigger"
manage state machine execution by cli
How to stop all running Step Functions of a specific state machine?
It is likely that your use-case could benefit from the callback pattern which will cause your state machine execution to wait for an event for the $$.Task.Token to be received. You can set a timeout by providing a HeartbeatSeconds which will cause the task to fail with States.Timeout.

Is it possible to insert a Horizontal Rule with Google Docs API?

I've been working on a project that needs to insert both text and other types of elements into a Google Docs Document, using PHP. I'm able to insert text using the following code:
$requests = [];
```
$requests[] = new \Google_Service_Docs_Request(
['insertText' => ['text' => 'Text to insert',
'location' => ['index' => $insertionIndex],
],
]);
```
$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$docsService->documents->batchUpdate($documentID, $batchUpdateRequest);
I can also insert a page break with a similar call:
$requests = [];
```
$requests[] = new \Google_Service_Docs_Request(
['insertPageBreak' => ['location' => ['index' => $insertionIndex],
],
]);
```
$batchUpdateRequest = new \Google_Service_Docs_BatchUpdateDocumentRequest(['requests' => $requests]);
$docsService->documents->batchUpdate($documentID, $batchUpdateRequest);
Both of the above work fine (and as per Google's recommendations when I am carrying out multiple insertions I am working backwards). What I need to be able to do is add a horizontal rule to the document. I know Google Docs allows the manual insertion of them and Apps Script supports insertHorizontalRule but the Docs API doesn't seem to have an equivalent. I have searched here, Google, and the API documentation and can't find any reference to it. Could someone tell me if it is possible? If it is possible, what is the correct request type?
It's seems additionally strange that there isn't a documented way of inserting them, and yet you can query the contents of an existing document and any that are in the document are reported back to you as part of its structure.
For clarity of purpose, I am trying to append the contents of one Google Doc to the another. If anyone knows of a better way to do this than consuming the source document element by element and creating a request to add those elements to the destination document, that would bypass the need to handle inserting a horizontal rule.
You want to insert the horizontal rule to Google Document using Docs API.
You want to achieve this using php.
You have already been able to get and put the values for Google Document using Docs API.
I could understand like above. Unfortunately, in the current stage, it seems that there are no methods for adding the horizontal rule in Google Docs API yet, while "horizontalRule" can be retrieved by documents.get. Docs API is growing now. So this might be added in the future update.
So in the current stage, it is required to use the workaround for this.
Pattern 1:
In this pattern, the horizontal rule is added to Google Document using Web Apps created by Google Apps Script as an API.
Usage:
1. Set Web Apps Script:
Please copy and paste the following script to the script editor for Google Apps Script.
function doGet(e) {
DocumentApp.openById(e.parameter.id).getBody().insertHorizontalRule(Number(e.parameter.index) - 1);
return ContentService.createTextOutput("Done");
}
2. Deploy Web Apps:
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
Select "Anyone, even anonymous" for "Who has access to the app:".
This setting is for a test situation.
You can also access with the access token by setting "Only myself" instead of "Anyone, even anonymous".
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
3. Use Web Apps as an API:
The following script is for PHP. Please set the query parameter of id and index. id is the Google Document ID. When index=1 is set, the horizontal rule is inserted to the top of body in Document. In this case, index means each row in the Google Document.
$url = 'https://script.google.com/macros/s/###/exec?id=###&index=1';
$curl = curl_init();
$option = [
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_FOLLOWLOCATION => true,
];
curl_setopt_array($curl, $option);
$response = curl_exec($curl);
$result = json_decode($response, true);
curl_close($curl);
Pattern 2:
I think that your proposal of I'm also going to look at possible inserting a thin table with a top border line as a replacement for a horizontal rule. can be also used as the workaround. For achieving this, the script is as follows.
When this script is run, new table that has the line of only top is created to the top of document. Before you run the script, please set $documentId. In this case, please set Google_Service_Docs::DOCUMENTS to the scopes.
Sample script:
$documentId = '###';
$index = 1;
$style = [
'width' => ['magnitude' => 0, 'unit' => 'PT'],
'dashStyle' => 'SOLID',
'color' => ['color' => ['rgbColor' => ['blue' => 1, 'green' => 1, 'red' => 1]]]
];
$requests = [
new Google_Service_Docs_Request([
'insertTable' => [
'location' => ['index' => $index],
'columns' => 1,
'rows' => 1
]
]),
new Google_Service_Docs_Request([
'updateTableCellStyle' => [
'tableCellStyle' => [
'borderBottom' => $style,
'borderLeft' => $style,
'borderRight' => $style,
],
'tableStartLocation' => ['index' => $index + 1],
'fields' => 'borderBottom,borderLeft,borderRight'
]
])
];
$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest([
'requests' => $requests
]);
$result = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
References:
Web Apps
insertHorizontalRule()
Method: documents.batchUpdate

Sending a JSON payload to a Google Cloud Task

I'm likely missing something incredibly obvious, but in the project I'm working on I've got to send many jobs from a CSV of info to be processed asynchronously and Google App Engine's current way is through their new (beta) Cloud Tasks mechanism.
It will accept a payload as part of the task, so I was going to send a JSON array with each job's pertinent data... except that the only way to dictate the "Content-Type: application/json" header is during creation of the task object.
I'm using Google's own cloud-tasks 0.5.0 library.
Here is what I've been attempting, since it seems this is how most other non-cURL HTTP POST requests would accept the Content-Type header...
require_once 'vendor/autoload.php';
use Google\Cloud\Tasks\V2beta3\AppEngineHttpQueue;
use Google\Cloud\Tasks\V2beta3\CloudTasksClient;
use Google\Cloud\Tasks\V2beta3\Queue;
use Google\Cloud\Tasks\V2beta3\Task;
<<< ...lots of cruft omitted... >>>
$json_payload = json_encode(
array(
"batch" => $operation_time,
"order" => $csvln[0],
"customer" => $csvln[1],
"email" => $csvln[2],
"salesperson" => $csvln[3]
)
);
//Create each of the tasks in the queue
$options = [
'http' => [
'header' => "Content-type: application/json",
'method' => 'POST',
'content' => $json_payload
]
];
$task = new Task($options);
Any help would be immensely appreciated!
You can load a task into the Task Queue with a pre-defined payload using an App Engine HTTP Request from the Cloud Tasks PHP Client Library.
After you defined the Task, you can use the setter methods provided to you by AppEngineHttpRequest to construct your HTTP object with any required headers. This will also allow to assign the payload.
Below is a simple snippet showing how to attach a task with a payload to the default queue:
use Google\Cloud\Tasks\V2beta3\AppEngineHttpRequest;
use Google\Cloud\Tasks\V2beta3\HttpMethod;
use Google\Cloud\Tasks\V2beta3\Task;
//Preparing the payload
$json_payload = json_encode(
array(
"batch" => date("h:i:sa"),
"order" => "Payload-0000",
"customer" => "Payload-0001",
"email" => "Payload-0002",
"salesperson" => "Payload-0003"
)
);
//Create and configure the task
$httpR=new AppEngineHttpRequest();
$httpR->setBody($json_payload);
$httpR->setHeaders(['Content-type'=>'application/json']);
$httpR->setHttpMethod(HttpMethod::POST);
$httpR->setRelativeUri("/example_task_handler");
$task = new Task();
$task->setAppEngineHttpRequest($httpR);
Also consider updating your library as the current version is v0.86.0 which it will allow the assignation of headers even after the creation of the task object.

PHP request hangs when using guzzle

I have the following code:
$client = new GuzzleHttp\Client(
array(
'base_uri' => 'https://somesite.com'
)
);
$response = $client->request('POST', '/api', [
'form_params' => array(
'action' => 'getusers',
'api_key' => $_POST['key'],
'id' => $_POST['id']
)
]);
When multiple users are accessing the same page with the following code above, other users waits for the first or recent request to finish before loading its request.
I'm not using any session.
I have tag curl because guzzle is built on top of it. Maybe it has something to do with it?
Any workaround for this?
using xhr won't fix it because the site I'm requesting for the API does not accept other origins.
Check available PHP processes if you are using PHP FPM. It has a status page (the setup is described there) to get this information.
If all the workers are busy, then client's requests will wait. You need to increase the amount of workers to be able to process more requests at once.

delete oldest object from S3

I have a script that does a backup of my system every day. In the end I get 3 zip files each day and they get stored to S3. What I'd like to do is always keep a week or 10 days worth of these backups. After the 10th day, delete the oldest 3 zip files from S3. Any ideas on how I could tackle this. I don't see a way I could query the date modified to find the oldest.
I'm using the S3 PHP SDK. For reference, here is what I do to create the objects.
<?php
require_once 'AWSSDKforPHP/sdk.class.php';
define('BACKUPDIR','/backups/');
$backup1="backup1_".time().".zip";
$backup2="backup2_".time().".zip";
$backup3="backup3_".time().".zip";
$s3 = new AmazonS3();
$s3->create_object('mybucket', 'backups/'.$backup1, array(
'fileUpload' => BACKUPDIR.$backup1,
'acl' => $s3::ACL_PRIVATE
));
$s3->create_object('mybucket', 'backups/'.$backup2, array(
'fileUpload' => BACKUPDIR.$backup2,
'acl' => $s3::ACL_PRIVATE
));
$s3->create_object('mybucket', 'backups/'.$backup3, array(
'fileUpload' => BACKUPDIR.$backup3,
'acl' => $s3::ACL_PRIVATE
));
?>
Using list_object requires a lot more work to parse so instead I used object expiration. Nothing to do here other than to let S3 handle it. All I have to do is add the expiry:
$s3->create_object('mybucket', $backup1, array(
'fileUpload' => BACKUPDIR.$backup1,
'acl' => $s3::ACL_PRIVATE,
'headers' => array(
'Expires' => gmdate(CFUtilities::DATE_FORMAT_RFC2616, strtotime('+10 days'))
)
));
Now S3 will clean this up automatically after 10 days. Perfect for me when handling backup files.
Use a GET Bucket (list objects) API call, as documented here:
http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketGET.html
This returns a list of all items in the bucket along with some meta data for every item, including the date on which the item was last modified. You can then use PHP to figure out which of these files you want to delete and use a DELETE Object API call to delete them :)

Categories