Compare commits

..

43 Commits

Author SHA1 Message Date
Koushik Dey c8fbd76ede Sending a warning instead of throwing error when KUBECONFIG is missing. (#141) 2021-07-27 18:17:13 +05:30
Koushik Dey ec2a943cdd Removing optional input arguments from the action (#139) 2021-06-24 11:46:30 +05:30
Jyotsna 9a12be5d3d Users/jysin/pm feedback changes for v1.3 (#98)
* Changed dockerfile, manifest, helmchart links and README
2021-01-07 12:53:01 +05:30
Jyotsna d4a7d27ca4 Bug fix for dockerfile path v1.3 (#95)
* Bug fix for dockerfile path
2020-12-30 22:18:13 +05:30
Jyotsna 5920a5b1b9 Adding annotation new changes to v1.3 (#83)
* Adding new traceability fields to annotations
2020-12-29 17:03:52 +05:30
Ajinkya 9793dbc8aa Fixing issues found in bug bash. (#73) 2020-11-02 11:09:45 +05:30
Koushik Dey e1ddefa019 Merge pull request #65 from Azure/users/koushdey/workflowAnnotations-1.3
Annotation and Label changes to handle multiple workflows across branches
2020-09-22 13:42:38 +05:30
Koushik Dey a4d28e7b97 Updated package and node modules 2020-09-21 18:25:10 +05:30
Koushik Dey 5902071a20 Annotation and Label changes to handle multiple workflows across branches(master) 2020-09-21 17:24:17 +05:30
Ajinkya 23de7006f4 Update node_modules 2020-09-18 12:52:14 +05:30
Ajinkya 47741599e5 Freeze packages to latest available versions 2020-09-18 12:51:11 +05:30
Ajinkya 68ed252e91 Committing changes in js files 2020-09-17 13:02:22 +05:30
Ajinkya 309ae69061 Adding node_modules 2020-09-17 13:00:55 +05:30
Sundar 29552c24a9 Blue green strategy - Refined some details. (#51)
* Refined some details.

* addressed comments

* updates readme

* Readme cleanup (#1)

* Small updates to readme

* added identified service terminology

* Adressed PR comments

* Added workflow to trigger L2 tests

* Renamed workflow file name

* Trigger integration tests through script and disable post check-in trigger.

Co-authored-by: Anirudh Raghunath <46741940+anraghun@users.noreply.github.com>
Co-authored-by: ajinkya599 <11447401+ajinkya599@users.noreply.github.com>
2020-09-17 12:22:14 +05:30
koushdey d394c2bba2 Merge pull request #52 from Azure/users/koushdey/addAnnotationsResourceView-master
Introduce annotations relevant to resource view during deploy
2020-07-31 19:12:05 +05:30
Koushik Dey e643530d85 Addressed review comments and refactored annotateNamespace 2020-07-31 19:02:52 +05:30
Koushik Dey a4ebc55d69 Checks in annotateNamespace to not error during failed annotation 2020-07-15 17:54:06 +05:30
Koushik Dey 15e04b8f7e Introduce annotations relevant to resource view during deploy 2020-07-15 16:24:50 +05:30
Sundar b4bc3003e8 added blue green strategy (#47)
* added blue green strategy

* Addressed review comments

* addressed pr comments

* updated names in test

* addressed final pr comments
2020-07-13 08:59:05 +05:30
Tauhid Anjum c9b54fdae2 Merge pull request #46 from Azure/tauhid621/optionalForceFlag
force flag added
2020-06-20 00:45:15 +05:30
tauhid621 6773ba4167 force flag added 2020-06-19 22:12:02 +05:30
rgsubh f1898e0618 Merge from release to master for test cases (#41)
* Test Cases for deploy (#35)

* Test Cases for deploy

* Testing workflow

* Fixing an issue with test runs on remote

* Fixing an issue with test runs on remote

* Fixing an issue with test runs on remote

* Fixing an issue with test runs on remote

* Fixing an issue with test runs on remote

* Fixing an issue with test runs on remote

* Review Comments fix

* Review comments fix

* Reverting typescript export changes in previour PR (#39)
2020-06-08 14:41:27 +05:30
Justin Hutchings 11a48a4e1d Add CodeQL security scanning (#38) 2020-06-03 11:25:20 +05:30
Anirudh 6da51b24cd Modified the description to optimise marketplace search (#31)
* modified description to optimise search

* modified wording

* added the AKS keyword

Co-authored-by: Anirudh Raghunath <void@Anirudhs-MacBook-Pro.local>
Co-authored-by: Anirudh Raghunath <void@MININT-G1P7G69.fareast.corp.microsoft.com>
2020-05-06 15:00:44 +05:30
Usha N 99c4423993 Update README.md 2020-03-26 18:12:00 +05:30
shigupt202 eb22293c53 Merge pull request #17 from Azure/users/shigupt/addingKubectlDescribeOutputInLogs
Users/shigupt/adding kubectl describe output in logs
2020-01-27 14:07:58 +05:30
Shivam Gupta e4bc5e8873 Adding a varibale to indicate describe output is needed 2020-01-23 16:46:13 +05:30
shigupt202 a3bb31ec16 Merge pull request #16 from shigupt202/users/shigupt/trafficSplitAPIVersionUpdate
Users/shigupt/traffic split api version update
2020-01-17 13:59:05 +05:30
Shivam Gupta e7d77ef817 Added exception for null kubectl commands 2020-01-17 10:15:28 +05:30
Shivam Gupta fdacb8e073 Created const for traffic split api version prefix 2020-01-13 16:20:48 +05:30
Shivam Gupta 4c0e9cfbff PR fixes 2020-01-10 11:26:48 +05:30
Shivam Gupta 305d883d74 Added lib file 2020-01-09 16:59:07 +05:30
Shivam Gupta 4a2857109f Added support for kubectl describe output in logs 2020-01-09 16:00:06 +05:30
Shivam Gupta 0527303033 Updated identation 2020-01-09 13:58:58 +05:30
Shivam Gupta 31a423057f Adding lib changes 2020-01-09 12:27:50 +05:30
Shivam Gupta ad0b77acbe TrafficSplit API version update 2020-01-09 11:21:36 +05:30
Lennart Schoch 2a3bf64395 Filter imagePullSecrets to contain only non-empty values (#14) 2019-12-06 08:34:10 +05:30
Deepak Sattiraju 26d4801e5e Update README.md 2019-12-04 15:03:49 +05:30
Shashank Barsin 637684d130 Merge pull request #8 from Azure/shasb
Update documentation
2019-11-19 14:26:17 +05:30
Shashank Barsin b635499b62 Update documentation 2019-11-19 14:25:13 +05:30
Shashank Barsin e6399ba4e7 Merge pull request #7 from Azure/shasb
Update documentation
2019-11-19 14:18:07 +05:30
Shashank Barsin 6687f5458e Update documentation 2019-11-19 14:15:40 +05:30
Deepak Sattiraju be01c3f321 Deployment Strategy (#4) (#6) 2019-11-18 21:07:19 +05:30
302 changed files with 14917 additions and 21400 deletions
@@ -0,0 +1,32 @@
token=$1
commit=$2
repository=$3
prNumber=$4
frombranch=$5
tobranch=$6
getPayLoad() {
cat <<EOF
{
"event_type": "K8sDeployActionPR",
"client_payload":
{
"action": "CreateSecret",
"commit": "$commit",
"repository": "$repository",
"prNumber": "$prNumber",
"tobranch": "$tobranch",
"frombranch": "$frombranch"
}
}
EOF
}
response=$(curl -X POST -H "Authorization: token $token" https://api.github.com/repos/Azure/azure-actions-integration-tests/dispatches --data "$(getPayLoad)")
if [ "$response" == "" ]; then
echo "Integration tests triggered successfully"
else
echo "Triggering integration tests failed with: '$response'"
exit 1
fi
+52
View File
@@ -0,0 +1,52 @@
name: "Code scanning - action"
on:
push:
pull_request:
schedule:
- cron: '0 19 * * 0'
jobs:
CodeQL-Build:
# CodeQL runs on ubuntu-latest and windows-latest
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
+23
View File
@@ -0,0 +1,23 @@
name: "Trigger Integration tests"
on:
# push:
# branches:
# - master
# - 'releases/*'
pull_request:
branches:
- master
- 'releases/*'
jobs:
trigger-integration-tests:
name: Trigger Integration tests
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v2
with:
path: IntegrationTests
- name: Trigger Test run
run: |
bash ./IntegrationTests/.github/workflows/TriggerIntegrationTests.sh ${{ secrets.L2_REPO_TOKEN }} ${{ github.event.pull_request.head.sha }} ${{ github.repository }} ${{ github.event.pull_request.number }} ${{ github.event.pull_request.head.ref }} ${{ github.event.pull_request.base.ref }}
+172 -41
View File
@@ -1,101 +1,232 @@
# Deploy manifest action for Kubernetes
Use this action to bake and deploy manifests to Kubernetes clusters.
Assumes that the deployment target K8s cluster context was set earlier in the workflow by using either [`Azure/aks-set-context`](https://github.com/Azure/aks-set-context/tree/releases/v1) or [`Azure/k8s-set-context`](https://github.com/Azure/k8s-set-context/tree/releases/v1) # Deploy manifests action for Kubernetes
#### Artifact substitution This action can be used to deploy manifests to Kubernetes clusters.
The deploy action takes as input a list of container images which can be specified along with their tags or digests. The same is substituted into the non-templatized version of manifest files before applying to the cluster to ensure that the right version of the image is pulled by the cluster nodes.
#### Manifest stability This action requires that the cluster context be set earlier in the workflow by using either the [Azure/aks-set-context](https://github.com/Azure/aks-set-context/tree/releases/v1) action or the [Azure/k8s-set-context](https://github.com/Azure/k8s-set-context/tree/releases/v1) action.
Rollout status is checked for the Kubernetes objects deployed. This is done to incorporate stability checks while computing the task status as success/failure.
#### Secret handling If you are looking to automate your workflows to deploy to [Azure Web Apps](https://azure.microsoft.com/en-us/services/app-service/web/) and [Azure Web App for Containers](https://azure.microsoft.com/en-us/services/app-service/containers/), consider using [`Azure/webapps-deploy`](https://github.com/Azure/webapps-deploy) action.
The manifest files specfied as inputs are augmented with appropriate imagePullSecrets before deploying to the cluster.
#### Sample YAML to run a basic deployment ## Action capabilities
Following are the key capabilities of this action:
- **Artifact substitution**: The deploy action takes as input a list of container images which can be specified along with their tags or digests. The same is substituted into the non-templatized version of manifest files before applying to the cluster to ensure that the right version of the image is pulled by the cluster nodes.
- **Object stability checks**: Rollout status is checked for the Kubernetes objects deployed. This is done to incorporate stability checks while computing the action status as success/failure.
- **Secret handling**: The secret names specified as inputs in the action are used to augment the input manifest files with imagePullSecrets values before deploying to the cluster. Also, checkout the [Azure/k8s-create-secret](https://github.com/Azure/k8s-create-secret) action for creation of generic or docker-registry secrets in the cluster.
- **Deployment strategy** The action supports canary and blue-green deployment strategies:
- **Canary strategy**: Choosing canary strategy with this action leads to creation of workloads suffixed with '-baseline' and '-canary'. There are two methods of traffic splitting supported in the action:
- **Service Mesh Interface**: Service Mesh Interface abstraction allows for plug-and-play configuration with service mesh providers such as Linkerd and Istio. Meanwhile, this action takes away the hard work of mapping SMI's TrafficSplit objects to the stable, baseline and canary services during the lifecycle of the deployment strategy. Service mesh based canary deployments using this action are more accurate as service mesh providers enable granular percentage traffic split (via service registry and sidecar containers injected into pods alongside application containers).
- **Only Kubernetes (no service mesh)**: In the absence of service mesh, while it may not be possible to achieve exact percentage split at the request level, it is still possible to perform canary deployments by deploying -baseline and -canary workload variants next to the stable variant. The service routes requests to pods of all three workload variants as the selector-label constraints are met (KubernetesManifest will honor these when creating -baseline and -canary variants). This achieves the intended effect of routing only a portion of total requests to the canary.
- **Blue-Green strategy**: Choosing blue-green strategy with this action leads to creation of workloads suffixed with '-green'. There are three route-methods supported in the action:
*Terminolgy: An **identified** service is one that is supplied as part of the input manifest(s) and targets a workload in the supplied manifest(s).
- **Service route-method**: **Identified** services are configured to target the green deployments.
- **Ingress route-method**: Along with deployments, new services are created with '-green' suffix (for **identified** services), and the ingresses are in turn updated to target the new services.
- **SMI route-method**: A new [TrafficSplit](https://github.com/servicemeshinterface/smi-spec/blob/master/apis/traffic-split/v1alpha3/traffic-split.md) object is created for each **identified** service. The TrafficSplit object is updated to target the new deployments. **Note** that this works only if SMI is set up in the cluster.
Traffic is routed to the new workloads only after the time provided as `version-switch-buffer` input has passed. `promote` action creates workloads and services with new configurations but without any suffix. `reject` action routes traffic back to the old workloads and deletes the '-green' workloads.
## Action inputs
<table>
<thead>
<tr>
<th>Action inputs</th>
<th>Description</th>
</tr>
</thead>
<tr>
<td><code>namespace</code><br/>Namespace</td>
<td>(Optional) Namespace within the cluster to deploy to.</td>
</tr>
<tr>
<td><code>manifests</code><br/>Manifests</td>
<td>(Required) Path to the manifest files to be used for deployment</td>
</tr>
<tr>
<td><code>images</code><br/>Images</td>
<td>(Optional) Fully qualified resource URL of the image(s) to be used for substitutions on the manifest files. This multiline input accepts specifying multiple artifact substitutions in newline separated form. For example - <br>images: |<br>&nbsp&nbspcontosodemo.azurecr.io/foo:test1<br>&nbsp&nbspcontosodemo.azurecr.io/bar:test2<br>In this example, all references to contosodemo.azurecr.io/foo and contosodemo.azurecr.io/bar are searched for in the image field of the input manifest files. For the matches found, the tags test1 and test2 are substituted.</td>
</tr>
<tr>
<td><code>imagepullsecrets</code><br/>Image pull secrets</td>
<td>(Optional) Multiline input where each line contains the name of a docker-registry secret that has already been setup within the cluster. Each of these secret names are added under imagePullSecrets field for the workloads found in the input manifest files</td>
</tr>
<tr>
<td><code>strategy</code><br/>Strategy</td>
<td>(Optional) Deployment strategy to be used while applying manifest files on the cluster. Acceptable values: none/canary/blue-green. none - No deployment strategy is used when deploying. canary - Canary deployment strategy is used when deploying to the cluster. blue-green - Blue-Green deployment strategy is used when deploying to cluster.</td>
</tr>
<tr>
<td><code>traffic-split-method</code><br/>Traffic split method</td>
<td>(Optional) Acceptable values: pod/smi; Default value: pod <br>SMI: Percentage traffic split is done at request level using service mesh. Service mesh has to be setup by cluster admin. Orchestration of <a href="https://github.com/servicemeshinterface/smi-spec/blob/master/apis/traffic-split/v1alpha3/traffic-split.md" data-raw-source="TrafficSplit](https://github.com/deislabs/smi-spec/blob/master/traffic-split.md)">TrafficSplit</a> objects of SMI is handled by this action. <br>Pod: Percentage split not possible at request level in the absence of service mesh. So the percentage input is used to calculate the replicas for baseline and canary as a percentage of replicas specified in the input manifests for the stable variant.</td>
</tr>
<tr>
<td><code>percentage</code><br/>Percentage</td>
<td>(Required if strategy == canary) Percentage used to compute the number of replicas of &#39;-baseline&#39; and &#39;-canary&#39; varaints of the workloads found in manifest files. For the specified percentage input, if (percentage * numberOfDesirerdReplicas)/100 is not a round number, the floor of this number is used while creating &#39;-baseline&#39; and &#39;-canary&#39;<br/>Example: If Deployment hello-world was found in the input manifest file with &#39;replicas: 4&#39; and if &#39;strategy: canary&#39; and &#39;percentage: 25&#39; are given as inputs to the action, then the Deployments hello-world-baseline and hello-world-canary are created with 1 replica each. The &#39;-baseline&#39; variant is created with the same image and tag as the stable version (4 replica variant prior to deployment) while the &#39;-canary&#39; variant is created with the image and tag corresponding to the new changes being deployed</td>
</tr>
<tr>
<td><code>baseline-and-canary-replicas</code><br/>Baseline and canary replicas</td>
<td>(Optional; Relevant only if trafficSplitMethod == smi) When trafficSplitMethod == smi, as percentage traffic split is controlled in the service mesh plane, the actual number of replicas for canary and baseline variants could be controlled independently of the traffic split. For example, assume that the input Deployment manifest desired 30 replicas to be used for stable and that the following inputs were specified for the action - <br>&nbsp;&nbsp;&nbsp;&nbsp;strategy: canary<br>&nbsp;&nbsp;&nbsp;&nbsp;trafficSplitMethod: smi<br>&nbsp;&nbsp;&nbsp;&nbsp;percentage: 20<br>&nbsp;&nbsp;&nbsp;&nbsp;baselineAndCanaryReplicas: 1<br> In this case, stable variant will receive 80% traffic while baseline and canary variants will receive 10% each (20% split equally between baseline and canary). However, instead of creating baseline and canary with 3 replicas, the explicit count of baseline and canary replicas is honored. That is, only 1 replica each is created for baseline and canary variants.</td>
</tr>
<tr>
<td><code>route-method</code><br/>Route Method</td>
<td>(Optional; Relevant only if strategy==blue-green) Default value: service. Acceptable values: service/ingress/smi. Traffic is routed based on this input.
<br>Service: Service selector labels are updated to target '-green' workloads.
<br>Ingress: Ingress backends are updated to target the new '-green' services which in turn target '-green' deployments.
<br>SMI: A <a href="https://github.com/servicemeshinterface/smi-spec/blob/master/apis/traffic-split/v1alpha3/traffic-split.md" data-raw-source="TrafficSplit](https://github.com/deislabs/smi-spec/blob/master/traffic-split.md)">TrafficSplit</a> object is created for each required service to route traffic to new workloads.</td>
</tr>
<tr>
<td><code>version-switch-buffer</code><br/>Version Switch Buffer</td>
<td>(Optional; Relevant only if strategy==blue-green and action == deploy) Default value: 0. Acceptable values: 1-300. Waits for the given input in minutes before routing traffic to '-green' workloads.</td>
</tr>
<tr>
<td><code>action</code><br/>Action</td>
<td>(Required) Default value: deploy. Acceptable values: deploy/promote/reject. Promote or reject actions are used to promote or reject canary/blue-green deployments. Sample YAML snippets are provided below for guidance on how to use the same.</td>
</tr>
<tr>
<td><code>kubectl-version</code><br/>Kubectl version</td>
<td>(Optional) Version of kubectl client to be used for deploying the manifest to the cluster. If this input is left unspecified, latest version is used.</td>
</tr>
<tr>
<td><code>force</code><br/>Force</td>
<td>(Optional) Deploy when a previous deployment already exists. If true then '--force' argument is added to the apply command. Using '--force' argument is not recommended in production.</td>
</tr>
</table>
## Examples YAML snippets
### Basic deployment (without any deployment strategy)
```yaml ```yaml
- uses: Azure/k8s-deploy@v1 - uses: Azure/k8s-deploy@v1
with: with:
namespace: 'myapp' # optional namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} ' manifests: |
deployment.yaml
service.yaml
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
imagepullsecrets: | imagepullsecrets: |
image-pull-secret1 image-pull-secret1
image-pull-secret2 image-pull-secret2
manifests: '/manifests/*.*' kubectl-version: 'latest'
kubectl-version: 'latest' # optional
``` ```
### Deployment Strategies ### Deployment Strategies - Canary deployment without service mesh
#### Pod Canary
```yaml ```yaml
- uses: Azure/k8s-deploy@v1 - uses: Azure/k8s-deploy@v1
with: with:
namespace: 'myapp' # optional namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} ' images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
imagepullsecrets: | imagepullsecrets: |
image-pull-secret1 image-pull-secret1
image-pull-secret2 image-pull-secret2
manifests: '/manifests/*.*' manifests: |
deployment.yaml
service.yaml
strategy: canary strategy: canary
percentage: 20 percentage: 20
``` ```
Inorder to promote or reject your canary deployment use the following: ### To promote/reject the canary created by the above snippet, the following YAML snippet could be used:
```yaml ```yaml
- uses: Azure/k8s-deploy@v1 - uses: Azure/k8s-deploy@v1
with: with:
namespace: 'myapp' # optional namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} ' images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
imagepullsecrets: | imagepullsecrets: |
image-pull-secret1 image-pull-secret1
image-pull-secret2 image-pull-secret2
manifests: '/manifests/*.*' manifests: |
deployment.yaml
service.yaml
strategy: canary strategy: canary
percentage: 20 action: promote # substitute reject if you want to reject
action: promote # set to reject if you want to reject it
``` ```
#### SMI Canary ### Deployment Strategies - Canary deployment based on Service Mesh Interface
```yaml ```yaml
- uses: Azure/k8s-deploy@v1 - uses: Azure/k8s-deploy@v1
with: with:
namespace: 'myapp' # optional namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} ' images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
imagepullsecrets: | imagepullsecrets: |
image-pull-secret1 image-pull-secret1
image-pull-secret2 image-pull-secret2
manifests: '/manifests/*.*' manifests: |
deployment.yaml
service.yaml
strategy: canary strategy: canary
traffic-split-method: smi traffic-split-method: smi
percentage: 20 percentage: 20
baseline-and-canary-replicas: 1 baseline-and-canary-replicas: 1
``` ```
### To promote/reject the canary created by the above snippet, the following YAML snippet could be used:
Inorder to promote or reject your canary deployment use the following:
```yaml ```yaml
- uses: Azure/k8s-deploy@v1 - uses: Azure/k8s-deploy@v1
with: with:
namespace: 'myapp' # optional namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }} ' images: 'contoso.azurecr.io/myapp:${{ event.run_id }} '
imagepullsecrets: | imagepullsecrets: |
image-pull-secret1 image-pull-secret1
image-pull-secret2 image-pull-secret2
manifests: '/manifests/*.*' manifests: |
deployment.yaml
service.yaml
strategy: canary strategy: canary
traffic-split-method: smi traffic-split-method: smi
percentage: 20 action: reject # substitute reject if you want to reject
baseline-and-canary-replicas: 1 ```
action: promote # set to reject if you want to reject it ### Deployment Strategies - Blue-Green deployment with different route methods
```yaml
- uses: Azure/k8s-deploy@v1
with:
namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
imagepullsecrets: |
image-pull-secret1
image-pull-secret2
manifests: |
deployment.yaml
service.yaml
ingress.yml
strategy: blue-green
route-method: ingress # substitute with service/smi as per need
version-switch-buffer: 15
``` ```
Refer to the action metadata file for details about all the inputs https://github.com/Azure/k8s-deploy/blob/master/action.yml ### **To promote/reject the green workload created by the above snippet, the following YAML snippet could be used:**
## End to end workflow for building container images and deploying to an Azure Kubernetes Service cluster ```yaml
- uses: Azure/k8s-deploy@v1
with:
namespace: 'myapp'
images: 'contoso.azurecr.io/myapp:${{ event.run_id }}'
imagepullsecrets: |
image-pull-secret1
image-pull-secret2
manifests: |
deployment.yaml
service.yaml
ingress-yml
strategy: blue-green
route-method: ingress # should be the same as the value when action was deploy
action: promote # substitute reject if you want to reject
```
## End to end workflows
Following are a few examples of not just this action, but how this action could be used along with other container and k8s related actions for building images and deploying objects onto k8s clusters:
### Build container image and deploy to Azure Kubernetes Service cluster
```yaml ```yaml
on: [push] on: [push]
@@ -141,7 +272,7 @@ jobs:
demo-k8s-secret demo-k8s-secret
``` ```
## End to end workflow for building container images and deploying to a Kubernetes cluster ### Build container image and deploy to any Azure Kubernetes Service cluster
```yaml ```yaml
on: [push] on: [push]
+777
View File
@@ -0,0 +1,777 @@
import * as fs from 'fs';
import * as inputParam from '../src/input-parameters';
import * as fileHelper from '../src/utilities/files-helper';
import {
Kubectl,
} from '../src/kubectl-object-model';
import {
mocked
} from 'ts-jest/utils';
import * as kubectlUtils from '../src/utilities/kubectl-util';
var path = require('path');
const inputParamMock = mocked(inputParam, true);
var deploymentYaml = "";
import * as blueGreenHelper from '../src/utilities/strategy-helpers/blue-green-helper';
import * as blueGreenHelperService from '../src/utilities/strategy-helpers/service-blue-green-helper';
import * as blueGreenHelperIngress from '../src/utilities/strategy-helpers/ingress-blue-green-helper';
import * as blueGreenHelperSMI from '../src/utilities/strategy-helpers/smi-blue-green-helper';
beforeAll(() => {
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'bg.yml'), 'utf8');
process.env["KUBECONFIG"] = 'kubeConfig';
});
test("deployBlueGreen - checks if deployment can be done, then deploys", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: undefined
};
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperService.deployBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({
"newFilePaths": "hello",
"result": ""
});
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
expect(kubeCtl.apply).toBeCalled();
});
test("blueGreenPromote - checks if in deployed state and then promotes", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: JSON.stringify({
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "testservice"
},
"spec": {
"selector": {
"app": "testapp",
"k8s.deploy.color": "green"
},
"ports": [{
"protocol": "TCP",
"port": 80,
"targetPort": 80
}]
}
})
};
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']);
expect(blueGreenHelperService.promoteBlueGreenService(kubeCtl, manifestObjects)).toMatchObject({});
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(kubeCtl.apply).toBeCalledWith("hello");
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
});
test("blueGreenReject - routes servcies to old deployment and deletes new deployment", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: JSON.stringify({
"apiVersion": "apps/v1beta1",
"kind": "Deployment",
"metadata": {
"name": "testapp",
"labels": {
"k8s.deploy.color": "none"
}
},
"spec": {
"selector": {
"matchLabels": {
"app": "testapp",
"k8s.deploy.color": "none"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"app": "testapp",
"k8s.deploy.color": "none"
}
},
"spec": {
"containers": [{
"name": "testapp",
"image": "testcr.azurecr.io/testapp",
"ports": [{
"containerPort": 80
}]
}]
}
}
}
})
};
kubeCtl.delete = jest.fn().mockReturnValue('');
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperService.rejectBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
});
test("blueGreenReject - deletes services if old deployment does not exist", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: undefined
};
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.delete = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperService.rejectBlueGreenService(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
});
test("isIngressRoute() - returns true if route-method is ingress", () => {
// default is service
expect(blueGreenHelper.isIngressRoute()).toBeFalsy();
});
test("isIngressRoute() - returns true if route-method is ingress", () => {
inputParamMock.routeMethod = 'ingress'
expect(blueGreenHelper.isIngressRoute()).toBeTruthy();
});
test("deployBlueGreenIngress - creates deployments, services and other non ingress objects", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: undefined
};
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperIngress.deployBlueGreenIngress(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({
"newFilePaths": "hello",
"result": ""
});
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(kubeCtl.apply).toBeCalledWith("hello");
});
test("blueGreenPromoteIngress - checks if in deployed state and then promotes ingress", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
let temp = {
stdout: JSON.stringify({
"apiVersion": "networking.k8s.io/v1beta1",
"kind": "Ingress",
"metadata": {
"name": "testingress",
"labels": {
"k8s.deploy.color": "green"
},
"annotations": {
"nginx.ingress.kubernetes.io/rewrite-target": "/"
}
},
"spec": {
"rules": [{
"http": {
"paths": [{
"path": "/testpath",
"pathType": "Prefix",
"backend": {
"serviceName": "testservice-green",
"servicePort": 80
}
}]
}
}]
}
})
};
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']);
//Invoke and assert
expect(blueGreenHelperIngress.promoteBlueGreenIngress(kubeCtl, manifestObjects)).toMatchObject({});
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(kubeCtl.apply).toBeCalledWith("hello");
});
test("blueGreenRejectIngress - routes ingress to stable services and deletes new deployments and services", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.delete = jest.fn().mockReturnValue('');
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperIngress.rejectBlueGreenIngress(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]);
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
});
test("isSMIRoute() - returns true if route-method is smi", () => {
inputParamMock.routeMethod = 'smi'
expect(blueGreenHelper.isSMIRoute()).toBeTruthy();
});
test("isSMIRoute() - returns true if route-method is smi", () => {
inputParamMock.routeMethod = 'ingress'
expect(blueGreenHelper.isSMIRoute()).toBeFalsy();
});
test("deployBlueGreenSMI - checks if deployment can be done, then deploys along this auxiliary services and trafficsplit", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: undefined
};
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
const kubectlUtilsMock = mocked(kubectlUtils, true);
kubectlUtilsMock.getTrafficSplitAPIVersion = jest.fn().mockReturnValue('split.smi-spec.io/v1alpha2');
//Invoke and assert
expect(blueGreenHelperSMI.deployBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({
"newFilePaths": "hello",
"result": ""
});
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
});
test("blueGreenPromoteSMI - checks weights of trafficsplit and then deploys", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
let temp = {
stdout: JSON.stringify({
"apiVersion": "split.smi-spec.io/v1alpha2",
"kind": "TrafficSplit",
"metadata": {
"name": "testservice-rollout"
},
"spec": {
"service": "testservice",
"backends": [{
"service": "testservice-stable",
"weight": 0
},
{
"service": "testservice-green",
"weight": 100
}
]
}
})
};
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const manifestObjects = blueGreenHelper.getManifestObjects(['manifests/bg.yaml']);
//Invoke and assert
expect(blueGreenHelperSMI.promoteBlueGreenSMI(kubeCtl, manifestObjects)).toMatchObject({});
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
});
test("blueGreenRejectSMI - routes servcies to old deployment and deletes new deployment, auxiliary services and trafficsplit", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: JSON.stringify({
"apiVersion": "apps/v1beta1",
"kind": "Deployment",
"metadata": {
"name": "testapp",
"labels": {
"k8s.deploy.color": "none"
}
},
"spec": {
"selector": {
"matchLabels": {
"app": "testapp",
"k8s.deploy.color": "none"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"app": "testapp",
"k8s.deploy.color": "none"
}
},
"spec": {
"containers": [{
"name": "testapp",
"image": "testcr.azurecr.io/testapp",
"ports": [{
"containerPort": 80
}]
}]
}
}
}
})
};
kubeCtl.delete = jest.fn().mockReturnValue('');
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperSMI.rejectBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]);
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-stable"]);
expect(kubeCtl.delete).toBeCalledWith(["TrafficSplit", "testservice-trafficsplit"]);
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
});
test("blueGreenRejectSMI - deletes service if stable deployment doesn't exist", () => {
const fileHelperMock = mocked(fileHelper, true);
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: undefined
};
kubeCtl.delete = jest.fn().mockReturnValue('');
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
//Invoke and assert
expect(blueGreenHelperSMI.rejectBlueGreenSMI(kubeCtl, ['manifests/bg.yaml'])).toMatchObject({});
expect(kubeCtl.delete).toBeCalledWith(["Deployment", "testapp-green"]);
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-green"]);
expect(kubeCtl.delete).toBeCalledWith(["Service", "testservice-stable"]);
expect(kubeCtl.delete).toBeCalledWith(["TrafficSplit", "testservice-trafficsplit"]);
expect(readFileSpy).toBeCalledWith("manifests/bg.yaml");
});
// other functions and branches
test("blueGreenRouteIngress - routes to green services in nextlabel is green", () => {
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
const fileHelperMock = mocked(fileHelper, true);
const ingEntList = [{
"apiVersion": "networking.k8s.io/v1beta1",
"kind": "Ingress",
"metadata": {
"name": "test-ingress",
"annotations": {
"nginx.ingress.kubernetes.io/rewrite-target": "/"
},
},
"spec": {
"rules": [{
"http": {
"paths": [{
"path": "/testpath",
"pathType": "Prefix",
"backend": {
"serviceName": "testservice",
"servicePort": 80
}
},
{
"path": "/testpath",
"pathType": "Prefix",
"backend": {
"serviceName": "random",
"servicePort": 80
}
}
]
}
}]
}
},
{
"apiVersion": "networking.k8s.io/v1beta1",
"kind": "Ingress",
"metadata": {
"name": "test-ingress",
"annotations": {
"nginx.ingress.kubernetes.io/rewrite-target": "/"
},
},
"spec": {
"rules": [{
"http": {
"paths": [{
"path": "/testpath",
"pathType": "Prefix",
"backend": {
"serviceName": "random",
"servicePort": 80
}
}]
}
}]
}
}
];
const serEntList = [{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "testservice"
},
"spec": {
"selector": {
"app": "testapp",
},
"ports": [{
"protocol": "TCP",
"port": 80,
"targetPort": 80
}]
}
}];
let serviceEntityMap = new Map<string, string>();
serviceEntityMap.set('testservice', 'testservice-green');
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue('hello');
kubeCtl.apply = jest.fn().mockReturnValue('');
//Invoke and assert
expect(blueGreenHelperIngress.routeBlueGreenIngress(kubeCtl, 'green', serviceEntityMap, ingEntList));
expect(kubeCtl.apply).toBeCalled();
expect(fileHelperMock.writeObjectsToFile).toBeCalled();
});
test("shouldWePromoteIngress - throws if routed ingress does not exist", () => {
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: undefined
}
const ingEntList = [{
"apiVersion": "networking.k8s.io/v1beta1",
"kind": "Ingress",
"metadata": {
"name": "test-ingress",
"annotations": {
"nginx.ingress.kubernetes.io/rewrite-target": "/"
}
},
"spec": {
"rules": [{
"http": {
"paths": [{
"path": "/testpath",
"pathType": "Prefix",
"backend": {
"serviceName": "testservice",
"servicePort": 80
}
}]
}
}]
}
}];
let serviceEntityMap = new Map<string, string>();
serviceEntityMap.set('testservice', 'testservice-green');
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
//Invoke and assert
expect(blueGreenHelperIngress.validateIngressesState(kubeCtl, ingEntList, serviceEntityMap)).toBeFalsy();
});
test("validateTrafficSplitState - throws if trafficsplit in wrong state", () => {
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: JSON.stringify({
"apiVersion": "split.smi-spec.io/v1alpha2",
"kind": "TrafficSplit",
"metadata": {
"name": "testservice-trafficsplit"
},
"spec": {
"service": "testservice",
"backends": [{
"service": "testservice-stable",
"weight": 100
},
{
"service": "testservice-green",
"weight": 0
}
]
}
})
}
const depEntList = [{
"apiVersion": "apps/v1beta1",
"kind": "Deployment",
"metadata": {
"name": "testapp",
},
"spec": {
"selector": {
"matchLabels": {
"app": "testapp",
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"app": "testapp",
}
},
"spec": {
"containers": [{
"name": "testapp",
"image": "testcr.azurecr.io/testapp",
"ports": [{
"containerPort": 80
}]
}]
}
}
}
}];
const serEntList = [{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "testservice"
},
"spec": {
"selector": {
"app": "testapp",
},
"ports": [{
"protocol": "TCP",
"port": 80,
"targetPort": 80
}]
}
}];
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
//Invoke and assert
expect(blueGreenHelperSMI.validateTrafficSplitsState(kubeCtl, serEntList)).toBeFalsy();
});
test("validateTrafficSplitState - throws if trafficsplit in wrong state", () => {
const kubeCtl: jest.Mocked < Kubectl > = new Kubectl("") as any;
let temp = {
stdout: JSON.stringify({
"apiVersion": "split.smi-spec.io/v1alpha2",
"kind": "TrafficSplit",
"metadata": {
"name": "testservice-trafficsplit"
},
"spec": {
"service": "testservice",
"backends": [{
"service": "testservice-stable",
"weight": 0
},
{
"service": "testservice-green",
"weight": 0
}
]
}
})
}
const depEntList = [{
"apiVersion": "apps/v1beta1",
"kind": "Deployment",
"metadata": {
"name": "testapp",
},
"spec": {
"selector": {
"matchLabels": {
"app": "testapp",
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"app": "testapp",
}
},
"spec": {
"containers": [{
"name": "testapp",
"image": "testcr.azurecr.io/testapp",
"ports": [{
"containerPort": 80
}]
}]
}
}
}
}];
const serEntList = [{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "testservice"
},
"spec": {
"selector": {
"app": "testapp",
},
"ports": [{
"protocol": "TCP",
"port": 80,
"targetPort": 80
}]
}
}];
kubeCtl.getResource = jest.fn().mockReturnValue(JSON.parse(JSON.stringify(temp)));
//Invoke and assert
expect(blueGreenHelperSMI.validateTrafficSplitsState(kubeCtl, serEntList)).toBeFalsy();
});
test("getSuffix() - returns BLUE_GREEN_SUFFIX if BLUE_GREEN_NEW_LABEL_VALUE is given, else emrty string", () => {
expect(blueGreenHelper.getSuffix('green')).toBe('-green');
});
test("getSuffix() - returns BLUE_GREEN_SUFFIX if BLUE_GREEN_NEW_LABEL_VALUE is given, else emrty string", () => {
expect(blueGreenHelper.getSuffix('random')).toBe('');
});
test("getServiceSpacLabel() - returns empty string if BLUE_GREEN_VERSION_LABEL in spec selector doesn't exist", () => {
let input = {
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "sample-deployment"
},
"spec": {
"selector": {
"matchLabels": {
"app": "sample",
"k8s.deploy.color": "green"
}
},
"template": {
"metadata": {
"labels": {
"app": "sample"
},
"annotations": {
"prometheus.io/scrape": "true",
"prometheus.io/port": "8888"
}
},
"spec": {
"containers": [{
"name": "sample",
"image": "tsugunt/sample:v34",
"ports": [{
"containerPort": 8888
}]
}]
}
}
}
}
expect(blueGreenHelperService.getServiceSpecLabel(input)).toBe('');
});
test("getDeploymentMatchLabels() - return false is input doesnt have matchLabels", () => {
let input = {
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "sample-service"
},
"spec": {
"selector": {
"app": "sample",
"k8s.deploy.color": "green"
},
"ports": [{
"protocol": "TCP",
"port": 80,
"targetPort": 8888,
"nodePort": 31002
}],
"type": "NodePort"
}
}
expect(blueGreenHelper.getDeploymentMatchLabels(input)).toBeFalsy();
});
test("getServiceSelector() - return false if spec selector does not exist", () => {
let input = {
"apiVersion": "networking.k8s.io/v1beta1",
"kind": "Ingress",
"metadata": {
"name": "test-ingress",
"annotations": {
"nginx.ingress.kubernetes.io/rewrite-target": "/"
}
},
"spec": {
"rules": [{
"http": {
"paths": [{
"path": "/testpath",
"pathType": "Prefix",
"backend": {
"serviceName": "test",
"servicePort": 80
}
}]
}
}]
}
}
expect(blueGreenHelper.getServiceSelector(input)).toBeFalsy();
});
+32
View File
@@ -0,0 +1,32 @@
apiVersion : apps/v1beta1
kind: Deployment
metadata:
name: testapp
spec:
selector:
matchLabels:
app: testapp
replicas: 1
template:
metadata:
labels:
app: testapp
spec:
containers:
- name: testapp
image: testcr.azurecr.io/testapp
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: testservice
spec:
selector:
app: testapp
ports:
- protocol: TCP
port: 80
targetPort: 80
---
+85
View File
@@ -0,0 +1,85 @@
apiVersion : apps/v1beta1
kind: Deployment
metadata:
name: testapp
spec:
selector:
matchLabels:
app: testapp
replicas: 1
template:
metadata:
labels:
app: testapp
spec:
containers:
- name: testapp
image: testcr.azurecr.io/testapp
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: testservice
spec:
selector:
app: testapp
ports:
- protocol: TCP
port: 80
targetPort: 80
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: testingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /testpath
pathType: Prefix
backend:
serviceName: testservice
servicePort: 80
---
apiVersion: v1
kind: ConfigMap
metadata:
name: testconfigmap
data:
# property-like keys; each key maps to a simple value
whats_this: "testing"
why_this: "testing"
---
apiVersion: v1
kind: Service
metadata:
name: testservice-2
spec:
selector:
app: testapp-2
ports:
- protocol: TCP
port: 80
targetPort: 80
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: testingress-1
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- http:
paths:
- path: /testpath
pathType: Prefix
backend:
serviceName: testnotservice
servicePort: 80
---
+89 -122
View File
@@ -7,10 +7,12 @@ import * as fs from 'fs';
import * as io from '@actions/io'; import * as io from '@actions/io';
import * as toolCache from '@actions/tool-cache'; import * as toolCache from '@actions/tool-cache';
import * as fileHelper from '../src/utilities/files-helper'; import * as fileHelper from '../src/utilities/files-helper';
import { workflowAnnotations } from '../src/constants'; import { getWorkflowAnnotationKeyLabel, getWorkflowAnnotationsJson } from '../src/constants';
import * as inputParam from '../src/input-parameters'; import * as inputParam from '../src/input-parameters';
import { Kubectl, Resource } from '../src/kubectl-object-model'; import { Kubectl, Resource } from '../src/kubectl-object-model';
import * as httpClient from '../src/utilities/httpClient';
import * as utility from '../src/utilities/utility';
import { getkubectlDownloadURL } from "../src/utilities/kubectl-util"; import { getkubectlDownloadURL } from "../src/utilities/kubectl-util";
import { mocked } from 'ts-jest/utils'; import { mocked } from 'ts-jest/utils';
@@ -36,14 +38,48 @@ const getAllPodsMock = {
const getNamespaceMock = { const getNamespaceMock = {
'code': 0, 'code': 0,
'stdout': '{"apiVersion": "v1","kind": "Namespace","metadata": {"annotations": {"workflow": ".github/workflows/workflow.yml","runUri": "https://github.com/testRepo/actions/runs/12345"}},"spec": {"finalizers": ["kubernetes"]},"status": {"phase": "Active"}}' 'stdout': '{"apiVersion": "v1","kind": "Namespace","metadata": {"annotations": {"githubWorkflow_c11401b9d232942bac19cbc5bc32b42d": "{\'run\': \'202489005\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflow1\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202489005\',\'commit\': \'currentCommit\',\'lastSuccessRunCommit\': \'lastCommit\',\'branch\': \'refs/heads/branch-rename\',\'deployTimestamp\': \'1597062957973\',\'dockerfilePaths\': \'{}\',\'manifestsPaths\': \'[]\',\'helmChartPaths\': \'[]\',\'provider\': \'GitHub\'}","githubWorkflow_21fd7a597282ca5adc05ba99018b3706": "{\'run\': \'202504411\',\'repository\': \'testUser/hello-kubernetes\',\'workflow\': \'workflowMaster\',\'jobName\': \'build-and-deploy\',\'createdBy\': \'testUser\',\'runUri\': \'https://github.com/testUser/hello-kubernetes/actions/runs/202504411\',\'commit\': \'currentCommit1\',\'lastSuccessRunCommit\': \'NA\',\'branch\': \'refs/heads/master\',\'deployTimestamp\': \'1597063919873\',\'dockerfilePaths\': \'{}\',\'manifestsPaths\': \'[]\',\'helmChartPaths\': \'[]\',\'provider\': \'GitHub\'}"}},"spec": {"finalizers": ["kubernetes"]},"status": {"phase": "Active"}}'
}; };
const getWorkflowsUrlResponse = {
'statusCode': httpClient.StatusCodes.OK,
'body': {
"total_count": 2,
"workflows": [
{
"id": 1477727,
"node_id": "MDg6V29ya2Zsb3cxNDYwNzI3",
"name": ".github/workflows/workflow.yml",
"path": ".github/workflows/workflow.yml",
"state": "active",
"created_at": "2020-06-03T23:41:06.000+05:30",
"updated_at": "2020-08-07T15:46:42.000+05:30",
"url": "https://api.github.com/repos/testUser/hello-kubernetes/actions/workflows/1460727",
"html_url": "https://github.com/testUser/hello-kubernetes/blob/master/.github/workflows/workflow.yml",
"badge_url": "https://github.com/testUser/hello-kubernetes/workflows/.github/workflows/workflow.yml/badge.svg"
},
{
"id": 1532230,
"node_id": "MDg6V29ya2Zsb3cxNTMyMzMw",
"name": "NewWorkflow",
"path": ".github/workflows/workflow1.yml",
"state": "active",
"created_at": "2020-06-11T16:05:23.000+05:30",
"updated_at": "2020-08-07T15:46:42.000+05:30",
"url": "https://api.github.com/repos/testUser/hello-kubernetes/actions/workflows/1532330",
"html_url": "https://github.com/testUser/hello-kubernetes/blob/master/.github/workflows/workflowNew.yml",
"badge_url": "https://github.com/testUser/hello-kubernetes/workflows/KoDeyi/badge.svg"
}
]
}
} as httpClient.WebResponse;
const resources: Resource[] = [{ type: "Deployment", name: "AppName" }]; const resources: Resource[] = [{ type: "Deployment", name: "AppName" }];
beforeEach(() => { beforeEach(() => {
deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'deployment.yml'), 'utf8'); deploymentYaml = fs.readFileSync(path.join(__dirname, 'manifests', 'deployment.yml'), 'utf8');
jest.spyOn(Date, 'now').mockImplementation(() => 1234561234567);
process.env["KUBECONFIG"] = 'kubeConfig'; process.env["KUBECONFIG"] = 'kubeConfig';
process.env['GITHUB_RUN_ID'] = '12345'; process.env['GITHUB_RUN_ID'] = '12345';
process.env['GITHUB_WORKFLOW'] = '.github/workflows/workflow.yml'; process.env['GITHUB_WORKFLOW'] = '.github/workflows/workflow.yml';
@@ -52,6 +88,7 @@ beforeEach(() => {
process.env['GITHUB_REPOSITORY'] = 'testRepo'; process.env['GITHUB_REPOSITORY'] = 'testRepo';
process.env['GITHUB_SHA'] = 'testCommit'; process.env['GITHUB_SHA'] = 'testCommit';
process.env['GITHUB_REF'] = 'testBranch'; process.env['GITHUB_REF'] = 'testBranch';
process.env['GITHUB_TOKEN'] = 'testToken';
}) })
test("setKubectlPath() - install a particular version", async () => { test("setKubectlPath() - install a particular version", async () => {
@@ -166,111 +203,6 @@ test("run() - deploy - Manifiest not provided", async () => {
expect(coreMock.setFailed).toBeCalledWith('No manifests supplied to deploy'); expect(coreMock.setFailed).toBeCalledWith('No manifests supplied to deploy');
}); });
test("run() - deploy - Only one manifest with no delimiters", async () => {
const kubectlVersion = 'v1.18.0'
coreMock.getInput = jest.fn().mockImplementation((name) => {
if (name == 'manifests') {
return "bg-smi.yml";
}
if (name == 'action') {
return 'deploy';
}
return kubectlVersion;
});
coreMock.setFailed = jest.fn();
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
fileUtility.chmodSync = jest.fn();
//Invoke and assert
await expect(action.run()).resolves.not.toThrow();
});
test("run() - deploy - Manifests provided by new line delimiter", async () => {
const kubectlVersion = 'v1.18.0'
coreMock.getInput = jest.fn().mockImplementation((name) => {
if (name == 'manifests') {
return "bg-smi.yml\n bg.yml\ndeployment.yml";
}
if (name == 'action') {
return 'deploy';
}
return kubectlVersion;
});
coreMock.setFailed = jest.fn();
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
fileUtility.chmodSync = jest.fn();
//Invoke and assert
await expect(action.run()).resolves.not.toThrow();
});
test("run() - deploy - Manifests provided by comma as a delimiter", async () => {
const kubectlVersion = 'v1.18.0'
coreMock.getInput = jest.fn().mockImplementation((name) => {
if (name == 'manifests') {
return "bg-smi.yml, bg.yml, deployment.yml";
}
if (name == 'action') {
return 'deploy';
}
return kubectlVersion;
});
coreMock.setFailed = jest.fn();
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
fileUtility.chmodSync = jest.fn();
//Invoke and assert
await expect(action.run()).resolves.not.toThrow();
});
test("run() - deploy - Manifests provided by both new line and comma as a delimiter", async () => {
const kubectlVersion = 'v1.18.0'
coreMock.getInput = jest.fn().mockImplementation((name) => {
if (name == 'manifests') {
return "bg-smi.yml\nbg.yml,deployment.yml";
}
if (name == 'action') {
return 'deploy';
}
return kubectlVersion;
});
coreMock.setFailed = jest.fn();
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
fileUtility.chmodSync = jest.fn();
//Invoke and assert
await expect(action.run()).resolves.not.toThrow();
});
test("run() - deploy - Manifests provided by both new line and comma and semi-colon as a delimiter", async () => {
const kubectlVersion = 'v1.18.0'
coreMock.getInput = jest.fn().mockImplementation((name) => {
if (name == 'manifests') {
return "bg-smi.yml\nbg.yml,deployment.yml;bg.yml";
}
if (name == 'action') {
return 'deploy';
}
return kubectlVersion;
});
coreMock.setFailed = jest.fn();
toolCacheMock.find = jest.fn().mockReturnValue(undefined);
toolCacheMock.downloadTool = jest.fn().mockReturnValue('downloadpath');
toolCacheMock.cacheFile = jest.fn().mockReturnValue('cachepath');
fileUtility.chmodSync = jest.fn();
//Invoke and assert
await expect(action.run()).resolves.not.toThrow();
});
test("deployment - deploy() - Invokes with no manifestfiles", async () => { test("deployment - deploy() - Invokes with no manifestfiles", async () => {
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any; const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
@@ -318,9 +250,11 @@ test("deployment - deploy() - Invokes with manifestfiles", async () => {
kubeCtl.describe = jest.fn().mockReturnValue(""); kubeCtl.describe = jest.fn().mockReturnValue("");
kubeCtl.annotateFiles = jest.fn().mockReturnValue(""); kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
kubeCtl.annotate = jest.fn().mockReturnValue(""); kubeCtl.annotate = jest.fn().mockReturnValue("");
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue(""); KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml); const readFileSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(() => deploymentYaml);
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
//Invoke and assert //Invoke and assert
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError(); await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
@@ -346,9 +280,11 @@ test("deployment - deploy() - deploy force flag on", async () => {
kubeCtl.describe = jest.fn().mockReturnValue(""); kubeCtl.describe = jest.fn().mockReturnValue("");
kubeCtl.annotateFiles = jest.fn().mockReturnValue(""); kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
kubeCtl.annotate = jest.fn().mockReturnValue(""); kubeCtl.annotate = jest.fn().mockReturnValue("");
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue(""); KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
const deploySpy = jest.spyOn(kubeCtl, 'apply').mockImplementation(() => applyResMock); const deploySpy = jest.spyOn(kubeCtl, 'apply').mockImplementation(() => applyResMock);
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
//Invoke and assert //Invoke and assert
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError(); await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
@@ -356,13 +292,20 @@ test("deployment - deploy() - deploy force flag on", async () => {
deploySpy.mockRestore(); deploySpy.mockRestore();
}); });
test("deployment - deploy() - Annotate resources", async () => { test("deployment - deploy() - Annotate & label resources", async () => {
var deploymentConfig: utility.DeploymentConfig = { manifestFilePaths :['manifests/deployment.yaml'], helmChartFilePaths : [], dockerfilePaths : {} } ;
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('currentCommit', '.github/workflows/workflow.yml', deploymentConfig);
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true); const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue(""); KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true); const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources); KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
const fileHelperMock = mocked(fileHelper, true); const fileHelperMock = mocked(fileHelper, true);
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue(["~/Deployment_testapp_currentTimestamp"]); const fsMock = (mocked(fs, true));
fileHelperMock.getTempDirectory = jest.fn().mockReturnValue("~/Deployment_testapp_currentTimestamp");
fsMock.writeFileSync =jest.fn().mockReturnValue("");
jest.spyOn(utility, 'getWorkflowFilePath').mockImplementation(() => Promise.resolve(process.env.GITHUB_WORKFLOW));
jest.spyOn(utility, 'getDeploymentConfig').mockImplementation(()=> Promise.resolve(deploymentConfig));
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any; const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
kubeCtl.apply = jest.fn().mockReturnValue(""); kubeCtl.apply = jest.fn().mockReturnValue("");
kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock); kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock);
@@ -370,21 +313,31 @@ test("deployment - deploy() - Annotate resources", async () => {
kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9"); kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9");
kubeCtl.annotateFiles = jest.fn().mockReturnValue(""); kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
kubeCtl.annotate = jest.fn().mockReturnValue(""); kubeCtl.annotate = jest.fn().mockReturnValue("");
kubeCtl.labelFiles = jest.fn();
//Invoke and assert //Invoke and assert
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError(); await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"], workflowAnnotations, true); expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"], annotationKeyValStr);
expect(kubeCtl.annotate).toBeCalledTimes(2); expect(kubeCtl.annotate).toBeCalledTimes(2);
expect(kubeCtl.labelFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"],
[`workflowFriendlyName=workflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
}); });
test("deployment - deploy() - Skip Annotate namespace", async () => { test("deployment - deploy() - Annotate & label resources for a new workflow", async () => {
process.env['GITHUB_REPOSITORY'] = 'test1Repo'; process.env.GITHUB_WORKFLOW = '.github/workflows/NewWorkflow.yml';
var deploymentConfig: utility.DeploymentConfig = { manifestFilePaths :['manifests/deployment.yaml'], helmChartFilePaths : [], dockerfilePaths : {} } ;
let annotationKeyValStr = getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW) + '=' + getWorkflowAnnotationsJson('NA', '.github/workflows/NewWorkflow.yml', deploymentConfig);
const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true); const KubernetesManifestUtilityMock = mocked(KubernetesManifestUtility, true);
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue(""); KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true); const KubernetesObjectUtilityMock = mocked(KubernetesObjectUtility, true);
KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources); KubernetesObjectUtilityMock.getResources = jest.fn().mockReturnValue(resources);
const fileHelperMock = mocked(fileHelper, true); const fileHelperMock = mocked(fileHelper, true);
fileHelperMock.writeObjectsToFile = jest.fn().mockReturnValue(["~/Deployment_testapp_currentTimestamp"]); const fsMock = (mocked(fs, true));
fileHelperMock.getTempDirectory = jest.fn().mockReturnValue("~/Deployment_testapp_currentTimestamp");
fsMock.writeFileSync =jest.fn().mockReturnValue("");
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(getWorkflowsUrlResponse));
jest.spyOn(utility, 'getDeploymentConfig').mockImplementation(()=> Promise.resolve(deploymentConfig));
const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any; const kubeCtl: jest.Mocked<Kubectl> = new Kubectl("") as any;
kubeCtl.apply = jest.fn().mockReturnValue(""); kubeCtl.apply = jest.fn().mockReturnValue("");
kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock); kubeCtl.getResource = jest.fn().mockReturnValue(getNamespaceMock);
@@ -392,14 +345,14 @@ test("deployment - deploy() - Skip Annotate namespace", async () => {
kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9"); kubeCtl.getNewReplicaSet = jest.fn().mockReturnValue("testpod-776cbc86f9");
kubeCtl.annotateFiles = jest.fn().mockReturnValue(""); kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
kubeCtl.annotate = jest.fn().mockReturnValue(""); kubeCtl.annotate = jest.fn().mockReturnValue("");
kubeCtl.labelFiles = jest.fn();
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
//Invoke and assert //Invoke and assert
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError(); await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp"], workflowAnnotations, true); expect(kubeCtl.annotate).toHaveBeenNthCalledWith(1, 'namespace', 'default', annotationKeyValStr);
expect(kubeCtl.annotate).toBeCalledTimes(1); expect(kubeCtl.annotateFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"], annotationKeyValStr);
expect(consoleOutputSpy).toHaveBeenNthCalledWith(2, `::debug::Skipping 'annotate namespace' as namespace annotated by other workflow` + os.EOL) expect(kubeCtl.annotate).toBeCalledTimes(2);
expect(kubeCtl.labelFiles).toBeCalledWith(["~/Deployment_testapp_currentTimestamp/deployment.yaml"],
[`workflowFriendlyName=NewWorkflow.yml`, `workflow=${getWorkflowAnnotationKeyLabel(process.env.GITHUB_WORKFLOW)}`]);
}); });
test("deployment - deploy() - Annotate resources failed", async () => { test("deployment - deploy() - Annotate resources failed", async () => {
@@ -421,10 +374,24 @@ test("deployment - deploy() - Annotate resources failed", async () => {
kubeCtl.describe = jest.fn().mockReturnValue(""); kubeCtl.describe = jest.fn().mockReturnValue("");
kubeCtl.annotateFiles = jest.fn().mockReturnValue(""); kubeCtl.annotateFiles = jest.fn().mockReturnValue("");
kubeCtl.annotate = jest.fn().mockReturnValue(annotateMock); kubeCtl.annotate = jest.fn().mockReturnValue(annotateMock);
kubeCtl.labelFiles = jest.fn().mockReturnValue("");
KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue(""); KubernetesManifestUtilityMock.checkManifestStability = jest.fn().mockReturnValue("");
const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation(); const consoleOutputSpy = jest.spyOn(process.stdout, "write").mockImplementation();
//Invoke and assert //Invoke and assert
await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError(); await expect(deployment.deploy(kubeCtl, ['manifests/deployment.yaml'], undefined)).resolves.not.toThrowError();
expect(consoleOutputSpy).toHaveBeenNthCalledWith(2, '::warning::kubectl annotate failed' + os.EOL) expect(consoleOutputSpy).toHaveBeenNthCalledWith(1, '::warning::kubectl annotate failed' + os.EOL)
});
test("utility - getWorkflowFilePath() - Get workflow file path under API failure", async () => {
//Mocks
const errorWebResponse = {
'statusCode': httpClient.StatusCodes.UNAUTHORIZED,
'body': {}
} as httpClient.WebResponse
jest.spyOn(httpClient, 'sendRequest').mockImplementation(() => Promise.resolve(errorWebResponse));
//Invoke and assert
await expect(utility.getWorkflowFilePath(process.env.GITHUB_TOKEN)).resolves.not.toThrowError;
await expect(utility.getWorkflowFilePath(process.env.GITHUB_TOKEN)).resolves.toBe(process.env.GITHUB_WORKFLOW);
}); });
+14 -5
View File
@@ -19,9 +19,17 @@ inputs:
description: 'Version of kubectl. Installs a specific version of kubectl binary' description: 'Version of kubectl. Installs a specific version of kubectl binary'
required: false required: false
strategy: strategy:
description: 'Deployment strategy to be used. Allowed values are none, canary' description: 'Deployment strategy to be used. Allowed values are none, canary and blue-green'
required: false required: false
default: 'none' default: 'none'
route-method:
description: 'Route based on service, ingress or SMI for blue-green strategy'
required: false
default: 'service'
version-switch-buffer:
description: 'Indicates the buffer time in minutes before the switch is made to the green version (max is 300 min ie. 5hrs)'
required: false
default: 0
traffic-split-method: traffic-split-method:
description: "Traffic split method to be used. Allowed values are pod, smi" description: "Traffic split method to be used. Allowed values are pod, smi"
required: false required: false
@@ -34,17 +42,18 @@ inputs:
description: 'Percentage of traffic redirect to canary deployment' description: 'Percentage of traffic redirect to canary deployment'
required: false required: false
default: 0 default: 0
args:
description: 'Arguments'
required: false
action: action:
description: 'deploy/promote/reject' description: 'deploy/promote/reject'
required: true required: true
default: 'deploy' default: 'deploy'
force: force:
description: 'Deploy when a previous deployment already exists. If true then --force argument is added to the apply command.' description: 'Deploy when a previous deployment already exists. If true then --force argument is added to the apply command'
required: false required: false
default: false default: false
token:
description: 'Github token'
default: ${{ github.token }}
required: true
branding: branding:
color: 'green' # optional, decorates the entry in the GitHub Marketplace color: 'green' # optional, decorates the entry in the GitHub Marketplace
+107 -52
View File
@@ -1,52 +1,107 @@
'use strict'; 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.promote = void 0; exports.promote = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const deploymentHelper = require("../utilities/strategy-helpers/deployment-helper"); const deploymentHelper = require("../utilities/strategy-helpers/deployment-helper");
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper"); const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper"); const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
const utils = require("../utilities/manifest-utilities"); const utils = require("../utilities/manifest-utilities");
const TaskInputParameters = require("../input-parameters"); const TaskInputParameters = require("../input-parameters");
const kubectl_object_model_1 = require("../kubectl-object-model"); const manifest_utilities_1 = require("../utilities/manifest-utilities");
function promote(ignoreSslErrors) { const KubernetesObjectUtility = require("../utilities/resource-object-utility");
return __awaiter(this, void 0, void 0, function* () { const models = require("../constants");
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, ignoreSslErrors); const KubernetesManifestUtility = require("../utilities/manifest-stability-utility");
if (!canaryDeploymentHelper.isCanaryDeploymentStrategy()) { const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
core.debug('Strategy is not canary deployment. Invalid request.'); const blue_green_helper_2 = require("../utilities/strategy-helpers/blue-green-helper");
throw ('InvalidPromotetActionDeploymentStrategy'); const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
} const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
let includeServices = false; const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
if (canaryDeploymentHelper.isSMICanaryStrategy()) { const kubectl_object_model_1 = require("../kubectl-object-model");
includeServices = true; function promote() {
// In case of SMI traffic split strategy when deployment is promoted, first we will redirect traffic to return __awaiter(this, void 0, void 0, function* () {
// Canary deployment, then update stable deployment and then redirect traffic to stable deployment const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
core.debug('Redirecting traffic to canary deployment'); if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
SMICanaryDeploymentHelper.redirectTrafficToCanaryDeployment(kubectl, TaskInputParameters.manifests); yield promoteCanary(kubectl);
core.debug('Deploying input manifests with SMI canary strategy'); }
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None'); else if (blue_green_helper_2.isBlueGreenDeploymentStrategy()) {
core.debug('Redirecting traffic to stable deployment'); yield promoteBlueGreen(kubectl);
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests); }
} else {
else { core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
core.debug('Deploying input manifests'); throw ('InvalidPromotetActionDeploymentStrategy');
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None'); }
} });
core.debug('Deployment strategy selected is Canary. Deleting canary and baseline workloads.'); }
try { exports.promote = promote;
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices); function promoteCanary(kubectl) {
} return __awaiter(this, void 0, void 0, function* () {
catch (ex) { let includeServices = false;
core.warning('Exception occurred while deleting canary and baseline workloads. Exception: ' + ex); if (canaryDeploymentHelper.isSMICanaryStrategy()) {
} includeServices = true;
}); // In case of SMI traffic split strategy when deployment is promoted, first we will redirect traffic to
} // Canary deployment, then update stable deployment and then redirect traffic to stable deployment
exports.promote = promote; core.debug('Redirecting traffic to canary deployment');
SMICanaryDeploymentHelper.redirectTrafficToCanaryDeployment(kubectl, TaskInputParameters.manifests);
core.debug('Deploying input manifests with SMI canary strategy');
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
core.debug('Redirecting traffic to stable deployment');
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
}
else {
core.debug('Deploying input manifests');
yield deploymentHelper.deploy(kubectl, TaskInputParameters.manifests, 'None');
}
core.debug('Deployment strategy selected is Canary. Deleting canary and baseline workloads.');
try {
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
}
catch (ex) {
core.warning('Exception occurred while deleting canary and baseline workloads. Exception: ' + ex);
}
});
}
function promoteBlueGreen(kubectl) {
return __awaiter(this, void 0, void 0, function* () {
// updated container images and pull secrets
let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(TaskInputParameters.manifests);
const manifestObjects = blue_green_helper_1.getManifestObjects(inputManifestFiles);
core.debug('deleting old deployment and making new ones');
let result;
if (blue_green_helper_2.isIngressRoute()) {
result = yield ingress_blue_green_helper_1.promoteBlueGreenIngress(kubectl, manifestObjects);
}
else if (blue_green_helper_2.isSMIRoute()) {
result = yield smi_blue_green_helper_1.promoteBlueGreenSMI(kubectl, manifestObjects);
}
else {
result = yield service_blue_green_helper_1.promoteBlueGreenService(kubectl, manifestObjects);
}
// checking stability of newly created deployments
const deployedManifestFiles = result.newFilePaths;
const resources = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([models.DiscoveryAndLoadBalancerResource.service]));
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
core.debug('routing to new deployments');
if (blue_green_helper_2.isIngressRoute()) {
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
}
else if (blue_green_helper_2.isSMIRoute()) {
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
smi_blue_green_helper_1.cleanupSMI(kubectl, manifestObjects.serviceEntityList);
}
else {
service_blue_green_helper_1.routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
}
});
}
+65 -36
View File
@@ -1,36 +1,65 @@
'use strict'; 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.reject = void 0; exports.reject = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper"); const canaryDeploymentHelper = require("../utilities/strategy-helpers/canary-deployment-helper");
const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper"); const SMICanaryDeploymentHelper = require("../utilities/strategy-helpers/smi-canary-deployment-helper");
const kubectl_object_model_1 = require("../kubectl-object-model"); const kubectl_object_model_1 = require("../kubectl-object-model");
const utils = require("../utilities/manifest-utilities"); const utils = require("../utilities/manifest-utilities");
const TaskInputParameters = require("../input-parameters"); const TaskInputParameters = require("../input-parameters");
function reject(ignoreSslErrors) { const service_blue_green_helper_1 = require("../utilities/strategy-helpers/service-blue-green-helper");
return __awaiter(this, void 0, void 0, function* () { const ingress_blue_green_helper_1 = require("../utilities/strategy-helpers/ingress-blue-green-helper");
const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, ignoreSslErrors); const smi_blue_green_helper_1 = require("../utilities/strategy-helpers/smi-blue-green-helper");
if (!canaryDeploymentHelper.isCanaryDeploymentStrategy()) { const blue_green_helper_1 = require("../utilities/strategy-helpers/blue-green-helper");
core.debug('Strategy is not canary deployment. Invalid request.'); const deployment_helper_1 = require("../utilities/strategy-helpers/deployment-helper");
throw ('InvalidRejectActionDeploymentStrategy'); function reject() {
} return __awaiter(this, void 0, void 0, function* () {
let includeServices = false; const kubectl = new kubectl_object_model_1.Kubectl(yield utils.getKubectl(), TaskInputParameters.namespace, true);
if (canaryDeploymentHelper.isSMICanaryStrategy()) { if (canaryDeploymentHelper.isCanaryDeploymentStrategy()) {
core.debug('Reject deployment with SMI canary strategy'); yield rejectCanary(kubectl);
includeServices = true; }
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests); else if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
} yield rejectBlueGreen(kubectl);
core.debug('Deployment strategy selected is Canary. Deleting baseline and canary workloads.'); }
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices); else {
}); core.debug('Strategy is not canary or blue-green deployment. Invalid request.');
} throw ('InvalidDeletetActionDeploymentStrategy');
exports.reject = reject; }
});
}
exports.reject = reject;
function rejectCanary(kubectl) {
return __awaiter(this, void 0, void 0, function* () {
let includeServices = false;
if (canaryDeploymentHelper.isSMICanaryStrategy()) {
core.debug('Reject deployment with SMI canary strategy');
includeServices = true;
SMICanaryDeploymentHelper.redirectTrafficToStableDeployment(kubectl, TaskInputParameters.manifests);
}
core.debug('Deployment strategy selected is Canary. Deleting baseline and canary workloads.');
canaryDeploymentHelper.deleteCanaryDeployment(kubectl, TaskInputParameters.manifests, includeServices);
});
}
function rejectBlueGreen(kubectl) {
return __awaiter(this, void 0, void 0, function* () {
let inputManifestFiles = deployment_helper_1.getManifestFiles(TaskInputParameters.manifests);
if (blue_green_helper_1.isIngressRoute()) {
yield ingress_blue_green_helper_1.rejectBlueGreenIngress(kubectl, inputManifestFiles);
}
else if (blue_green_helper_1.isSMIRoute()) {
yield smi_blue_green_helper_1.rejectBlueGreenSMI(kubectl, inputManifestFiles);
}
else {
yield service_blue_green_helper_1.rejectBlueGreenService(kubectl, inputManifestFiles);
}
});
}
+54 -39
View File
@@ -1,39 +1,54 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.workflowAnnotations = exports.workloadTypesWithRolloutStatus = exports.workloadTypes = exports.deploymentTypes = exports.ServiceTypes = exports.DiscoveryAndLoadBalancerResource = exports.KubernetesWorkload = void 0; exports.getWorkflowAnnotationKeyLabel = exports.getWorkflowAnnotationsJson = exports.workloadTypesWithRolloutStatus = exports.workloadTypes = exports.deploymentTypes = exports.ServiceTypes = exports.DiscoveryAndLoadBalancerResource = exports.KubernetesWorkload = void 0;
class KubernetesWorkload { class KubernetesWorkload {
} }
exports.KubernetesWorkload = KubernetesWorkload; exports.KubernetesWorkload = KubernetesWorkload;
KubernetesWorkload.pod = 'Pod'; KubernetesWorkload.pod = 'Pod';
KubernetesWorkload.replicaset = 'Replicaset'; KubernetesWorkload.replicaset = 'Replicaset';
KubernetesWorkload.deployment = 'Deployment'; KubernetesWorkload.deployment = 'Deployment';
KubernetesWorkload.statefulSet = 'StatefulSet'; KubernetesWorkload.statefulSet = 'StatefulSet';
KubernetesWorkload.daemonSet = 'DaemonSet'; KubernetesWorkload.daemonSet = 'DaemonSet';
KubernetesWorkload.job = 'job'; KubernetesWorkload.job = 'job';
KubernetesWorkload.cronjob = 'cronjob'; KubernetesWorkload.cronjob = 'cronjob';
class DiscoveryAndLoadBalancerResource { class DiscoveryAndLoadBalancerResource {
} }
exports.DiscoveryAndLoadBalancerResource = DiscoveryAndLoadBalancerResource; exports.DiscoveryAndLoadBalancerResource = DiscoveryAndLoadBalancerResource;
DiscoveryAndLoadBalancerResource.service = 'service'; DiscoveryAndLoadBalancerResource.service = 'service';
DiscoveryAndLoadBalancerResource.ingress = 'ingress'; DiscoveryAndLoadBalancerResource.ingress = 'ingress';
class ServiceTypes { class ServiceTypes {
} }
exports.ServiceTypes = ServiceTypes; exports.ServiceTypes = ServiceTypes;
ServiceTypes.loadBalancer = 'LoadBalancer'; ServiceTypes.loadBalancer = 'LoadBalancer';
ServiceTypes.nodePort = 'NodePort'; ServiceTypes.nodePort = 'NodePort';
ServiceTypes.clusterIP = 'ClusterIP'; ServiceTypes.clusterIP = 'ClusterIP';
exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset']; exports.deploymentTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset'];
exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob']; exports.workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset']; exports.workloadTypesWithRolloutStatus = ['deployment', 'daemonset', 'statefulset'];
exports.workflowAnnotations = [ function getWorkflowAnnotationsJson(lastSuccessRunSha, workflowFilePath, deploymentConfig) {
`run=${process.env['GITHUB_RUN_ID']}`, let annotationObject = {};
`repository=${process.env['GITHUB_REPOSITORY']}`, annotationObject["run"] = process.env.GITHUB_RUN_ID;
`workflow=${process.env['GITHUB_WORKFLOW']}`, annotationObject["repository"] = process.env.GITHUB_REPOSITORY;
`jobName=${process.env['GITHUB_JOB']}`, annotationObject["workflow"] = process.env.GITHUB_WORKFLOW;
`createdBy=${process.env['GITHUB_ACTOR']}`, annotationObject["workflowFileName"] = workflowFilePath.replace(".github/workflows/", "");
`runUri=https://github.com/${process.env['GITHUB_REPOSITORY']}/actions/runs/${process.env['GITHUB_RUN_ID']}`, annotationObject["jobName"] = process.env.GITHUB_JOB;
`commit=${process.env['GITHUB_SHA']}`, annotationObject["createdBy"] = process.env.GITHUB_ACTOR;
`branch=${process.env['GITHUB_REF']}`, annotationObject["runUri"] = `https://github.com/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
`deployTimestamp=${Date.now()}`, annotationObject["commit"] = process.env.GITHUB_SHA;
`provider=GitHub` annotationObject["lastSuccessRunCommit"] = lastSuccessRunSha;
]; annotationObject["branch"] = process.env.GITHUB_REF;
annotationObject["deployTimestamp"] = Date.now();
annotationObject["dockerfilePaths"] = deploymentConfig.dockerfilePaths;
annotationObject["manifestsPaths"] = deploymentConfig.manifestFilePaths;
annotationObject["helmChartPaths"] = deploymentConfig.helmChartFilePaths;
annotationObject["provider"] = "GitHub";
return JSON.stringify(annotationObject);
}
exports.getWorkflowAnnotationsJson = getWorkflowAnnotationsJson;
function getWorkflowAnnotationKeyLabel(workflowFilePath) {
const hashKey = require("crypto").createHash("MD5")
.update(`${process.env.GITHUB_REPOSITORY}/${workflowFilePath}`)
.digest("hex");
return `githubWorkflow_${hashKey}`;
}
exports.getWorkflowAnnotationKeyLabel = getWorkflowAnnotationKeyLabel;
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DockerExec = void 0;
const tool_runner_1 = require("./utilities/tool-runner");
class DockerExec {
constructor(dockerPath) {
this.dockerPath = dockerPath;
}
;
pull(image, args, silent) {
args = ['pull', image, ...args];
let result = this.execute(args, silent);
if (result.stderr != '' && result.code != 0) {
throw new Error(`docker images pull failed with: ${result.error}`);
}
}
inspect(image, args, silent) {
args = ['inspect', image, ...args];
let result = this.execute(args, silent);
if (result.stderr != '' && result.code != 0) {
throw new Error(`docker inspect call failed with: ${result.error}`);
}
return result.stdout;
}
execute(args, silent) {
const command = new tool_runner_1.ToolRunner(this.dockerPath);
command.arg(args);
return command.execSync({ silent: !!silent });
}
}
exports.DockerExec = DockerExec;
+35
View File
@@ -0,0 +1,35 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitHubClient = void 0;
const core = require("@actions/core");
const httpClient_1 = require("./utilities/httpClient");
class GitHubClient {
constructor(repository, token) {
this._repository = repository;
this._token = token;
}
getWorkflows() {
return __awaiter(this, void 0, void 0, function* () {
const getWorkflowFileNameUrl = `https://api.github.com/repos/${this._repository}/actions/workflows`;
const webRequest = new httpClient_1.WebRequest();
webRequest.method = "GET";
webRequest.uri = getWorkflowFileNameUrl;
webRequest.headers = {
Authorization: `Bearer ${this._token}`
};
core.debug(`Getting workflows for repo: ${this._repository}`);
const response = yield httpClient_1.sendRequest(webRequest);
return Promise.resolve(response);
});
}
}
exports.GitHubClient = GitHubClient;
+56 -40
View File
@@ -1,40 +1,56 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.forceDeployment = exports.args = exports.baselineAndCanaryReplicas = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0; exports.githubToken = exports.forceDeployment = exports.baselineAndCanaryReplicas = exports.versionSwitchBuffer = exports.routeMethod = exports.trafficSplitMethod = exports.deploymentStrategy = exports.canaryPercentage = exports.manifests = exports.imagePullSecrets = exports.containers = exports.namespace = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
exports.namespace = core.getInput('namespace'); exports.namespace = core.getInput('namespace');
exports.containers = core.getInput('images').split('\n'); exports.containers = core.getInput('images').split('\n');
exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0); exports.imagePullSecrets = core.getInput('imagepullsecrets').split('\n').filter(secret => secret.trim().length > 0);
exports.manifests = core.getInput('manifests').split(/[\n,;]+/).filter(manifest => manifest.trim().length > 0); exports.manifests = core.getInput('manifests').split('\n');
exports.canaryPercentage = core.getInput('percentage'); exports.canaryPercentage = core.getInput('percentage');
exports.deploymentStrategy = core.getInput('strategy'); exports.deploymentStrategy = core.getInput('strategy');
exports.trafficSplitMethod = core.getInput('traffic-split-method'); exports.trafficSplitMethod = core.getInput('traffic-split-method');
exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas'); exports.routeMethod = core.getInput('route-method');
exports.args = core.getInput('arguments'); exports.versionSwitchBuffer = core.getInput('version-switch-buffer');
exports.forceDeployment = core.getInput('force').toLowerCase() == 'true'; exports.baselineAndCanaryReplicas = core.getInput('baseline-and-canary-replicas');
if (!exports.namespace) { exports.forceDeployment = core.getInput('force').toLowerCase() == 'true';
core.debug('Namespace was not supplied; using "default" namespace instead.'); exports.githubToken = core.getInput("token");
exports.namespace = 'default'; if (!exports.namespace) {
} core.debug('Namespace was not supplied; using "default" namespace instead.');
try { exports.namespace = 'default';
const pe = parseInt(exports.canaryPercentage); }
if (pe < 0 || pe > 100) { if (!exports.githubToken) {
core.setFailed('A valid percentage value is between 0 and 100'); core.error("'token' input is not supplied. Set it to a PAT/GITHUB_TOKEN");
process.exit(1); }
} try {
} const pe = parseInt(exports.canaryPercentage);
catch (ex) { if (pe < 0 || pe > 100) {
core.setFailed("Enter a valid 'percentage' integer value "); core.setFailed('A valid percentage value is between 0 and 100');
process.exit(1); process.exit(1);
} }
try { }
const pe = parseInt(exports.baselineAndCanaryReplicas); catch (ex) {
if (pe < 0 || pe > 100) { core.setFailed("Enter a valid 'percentage' integer value ");
core.setFailed('A valid baseline-and-canary-replicas value is between 0 and 100'); process.exit(1);
process.exit(1); }
} try {
} const pe = parseInt(exports.baselineAndCanaryReplicas);
catch (ex) { if (pe < 0 || pe > 100) {
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value"); core.setFailed('A valid baseline-and-canary-replicas value is between 0 and 100');
process.exit(1); process.exit(1);
} }
}
catch (ex) {
core.setFailed("Enter a valid 'baseline-and-canary-replicas' integer value");
process.exit(1);
}
try {
const pe = parseInt(exports.versionSwitchBuffer);
if (pe < 0 || pe > 300) {
core.setFailed('Invalid buffer time, valid version-switch-buffer is a value more than or equal to 0 and lesser than or equal 300');
process.exit(1);
}
}
catch (ex) {
core.setFailed("Enter a valid 'version-switch-buffer' integer value");
process.exit(1);
}
+117 -114
View File
@@ -1,114 +1,117 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.Kubectl = void 0; exports.Kubectl = void 0;
const tool_runner_1 = require("./utilities/tool-runner"); const tool_runner_1 = require("./utilities/tool-runner");
class Kubectl { class Kubectl {
constructor(kubectlPath, namespace, ignoreSSLErrors) { constructor(kubectlPath, namespace, ignoreSSLErrors) {
this.kubectlPath = kubectlPath; this.kubectlPath = kubectlPath;
this.ignoreSSLErrors = !!ignoreSSLErrors; this.ignoreSSLErrors = !!ignoreSSLErrors;
if (!!namespace) { if (!!namespace) {
this.namespace = namespace; this.namespace = namespace;
} }
else { else {
this.namespace = 'default'; this.namespace = 'default';
} }
} }
apply(configurationPaths, force) { apply(configurationPaths, force) {
let applyArgs = ['apply', '-f', this.createInlineArray(configurationPaths)]; let applyArgs = ['apply', '-f', this.createInlineArray(configurationPaths)];
if (!!force) { if (!!force) {
console.log("force flag is on, deployment will continue even if previous deployment already exists"); console.log("force flag is on, deployment will continue even if previous deployment already exists");
applyArgs.push('--force'); applyArgs.push('--force');
} }
return this.execute(applyArgs); return this.execute(applyArgs);
} }
describe(resourceType, resourceName, silent) { describe(resourceType, resourceName, silent) {
return this.execute(['describe', resourceType, resourceName], silent); return this.execute(['describe', resourceType, resourceName], silent);
} }
getNewReplicaSet(deployment) { getNewReplicaSet(deployment) {
let newReplicaSet = ''; let newReplicaSet = '';
const result = this.describe('deployment', deployment, true); const result = this.describe('deployment', deployment, true);
if (result && result.stdout) { if (result && result.stdout) {
const stdout = result.stdout.split('\n'); const stdout = result.stdout.split('\n');
stdout.forEach((line) => { stdout.forEach((line) => {
if (!!line && line.toLowerCase().indexOf('newreplicaset') > -1) { if (!!line && line.toLowerCase().indexOf('newreplicaset') > -1) {
newReplicaSet = line.substr(14).trim().split(' ')[0]; newReplicaSet = line.substr(14).trim().split(' ')[0];
} }
}); });
} }
return newReplicaSet; return newReplicaSet;
} }
annotate(resourceType, resourceName, annotations, overwrite) { annotate(resourceType, resourceName, annotation) {
let args = ['annotate', resourceType, resourceName]; let args = ['annotate', resourceType, resourceName];
args = args.concat(annotations); args.push(annotation);
if (!!overwrite) { args.push(`--overwrite`);
args.push(`--overwrite`); return this.execute(args);
} }
return this.execute(args); annotateFiles(files, annotation) {
} let args = ['annotate'];
annotateFiles(files, annotations, overwrite) { args = args.concat(['-f', this.createInlineArray(files)]);
let args = ['annotate']; args.push(annotation);
args = args.concat(['-f', this.createInlineArray(files)]); args.push(`--overwrite`);
args = args.concat(annotations); return this.execute(args);
if (!!overwrite) { }
args.push(`--overwrite`); labelFiles(files, labels) {
} let args = ['label'];
return this.execute(args); args = args.concat(['-f', this.createInlineArray(files)]);
} args = args.concat(labels);
getAllPods() { args.push(`--overwrite`);
return this.execute(['get', 'pods', '-o', 'json'], true); return this.execute(args);
} }
getClusterInfo() { getAllPods() {
return this.execute(['cluster-info'], true); return this.execute(['get', 'pods', '-o', 'json'], true);
} }
checkRolloutStatus(resourceType, name) { getClusterInfo() {
return this.execute(['rollout', 'status', resourceType + '/' + name]); return this.execute(['cluster-info'], true);
} }
getResource(resourceType, name) { checkRolloutStatus(resourceType, name) {
return this.execute(['get', resourceType + '/' + name, '-o', 'json']); return this.execute(['rollout', 'status', resourceType + '/' + name]);
} }
getResources(applyOutput, filterResourceTypes) { getResource(resourceType, name) {
const outputLines = applyOutput.split('\n'); return this.execute(['get', resourceType + '/' + name, '-o', 'json']);
const results = []; }
outputLines.forEach(line => { getResources(applyOutput, filterResourceTypes) {
const words = line.split(' '); const outputLines = applyOutput.split('\n');
if (words.length > 2) { const results = [];
const resourceType = words[0].trim(); outputLines.forEach(line => {
const resourceName = JSON.parse(words[1].trim()); const words = line.split(' ');
if (filterResourceTypes.filter(type => !!type && resourceType.toLowerCase().startsWith(type.toLowerCase())).length > 0) { if (words.length > 2) {
results.push({ const resourceType = words[0].trim();
type: resourceType, const resourceName = JSON.parse(words[1].trim());
name: resourceName if (filterResourceTypes.filter(type => !!type && resourceType.toLowerCase().startsWith(type.toLowerCase())).length > 0) {
}); results.push({
} type: resourceType,
} name: resourceName
}); });
return results; }
} }
executeCommand(customCommand, args) { });
if (!customCommand) return results;
throw new Error('NullCommandForKubectl'); }
return args ? this.execute([customCommand, args]) : this.execute([customCommand]); executeCommand(customCommand, args) {
} if (!customCommand)
delete(args) { throw new Error('NullCommandForKubectl');
if (typeof args === 'string') return args ? this.execute([customCommand, args]) : this.execute([customCommand]);
return this.execute(['delete', args]); }
else delete(args) {
return this.execute(['delete'].concat(args)); if (typeof args === 'string')
} return this.execute(['delete', args]);
execute(args, silent) { else
if (this.ignoreSSLErrors) { return this.execute(['delete'].concat(args));
args.push('--insecure-skip-tls-verify'); }
} execute(args, silent) {
args = args.concat(['--namespace', this.namespace]); if (this.ignoreSSLErrors) {
const command = new tool_runner_1.ToolRunner(this.kubectlPath); args.push('--insecure-skip-tls-verify');
command.arg(args); }
return command.execSync({ silent: !!silent }); args = args.concat(['--namespace', this.namespace]);
} const command = new tool_runner_1.ToolRunner(this.kubectlPath);
createInlineArray(str) { command.arg(args);
if (typeof str === 'string') { return command.execSync({ silent: !!silent });
return str; }
} createInlineArray(str) {
return str.join(','); if (typeof str === 'string') {
} return str;
} }
exports.Kubectl = Kubectl; return str.join(',');
}
}
exports.Kubectl = Kubectl;
+91 -96
View File
@@ -1,96 +1,91 @@
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.run = void 0; exports.run = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const io = require("@actions/io"); const io = require("@actions/io");
const path = require("path"); const path = require("path");
const toolCache = require("@actions/tool-cache"); const toolCache = require("@actions/tool-cache");
const kubectl_util_1 = require("./utilities/kubectl-util"); const kubectl_util_1 = require("./utilities/kubectl-util");
const utility_1 = require("./utilities/utility"); const utility_1 = require("./utilities/utility");
const kubectl_object_model_1 = require("./kubectl-object-model"); const kubectl_object_model_1 = require("./kubectl-object-model");
const deployment_helper_1 = require("./utilities/strategy-helpers/deployment-helper"); const deployment_helper_1 = require("./utilities/strategy-helpers/deployment-helper");
const promote_1 = require("./actions/promote"); const promote_1 = require("./actions/promote");
const reject_1 = require("./actions/reject"); const reject_1 = require("./actions/reject");
let kubectlPath = ""; let kubectlPath = "";
function setKubectlPath() { function setKubectlPath() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (core.getInput('kubectl-version')) { if (core.getInput('kubectl-version')) {
const version = core.getInput('kubectl-version'); const version = core.getInput('kubectl-version');
kubectlPath = toolCache.find('kubectl', version); kubectlPath = toolCache.find('kubectl', version);
if (!kubectlPath) { if (!kubectlPath) {
kubectlPath = yield installKubectl(version); kubectlPath = yield installKubectl(version);
} }
} }
else { else {
kubectlPath = yield io.which('kubectl', false); kubectlPath = yield io.which('kubectl', false);
if (!kubectlPath) { if (!kubectlPath) {
const allVersions = toolCache.findAllVersions('kubectl'); const allVersions = toolCache.findAllVersions('kubectl');
kubectlPath = allVersions.length > 0 ? toolCache.find('kubectl', allVersions[0]) : ''; kubectlPath = allVersions.length > 0 ? toolCache.find('kubectl', allVersions[0]) : '';
if (!kubectlPath) { if (!kubectlPath) {
throw new Error('Kubectl is not installed, either add install-kubectl action or provide "kubectl-version" input to download kubectl'); throw new Error('Kubectl is not installed, either add install-kubectl action or provide "kubectl-version" input to download kubectl');
} }
kubectlPath = path.join(kubectlPath, `kubectl${utility_1.getExecutableExtension()}`); kubectlPath = path.join(kubectlPath, `kubectl${utility_1.getExecutableExtension()}`);
} }
} }
}); });
} }
function installKubectl(version) { function installKubectl(version) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (utility_1.isEqual(version, 'latest')) { if (utility_1.isEqual(version, 'latest')) {
version = yield kubectl_util_1.getStableKubectlVersion(); version = yield kubectl_util_1.getStableKubectlVersion();
} }
return yield kubectl_util_1.downloadKubectl(version); return yield kubectl_util_1.downloadKubectl(version);
}); });
} }
function checkClusterContext() { function checkClusterContext() {
if (!process.env["KUBECONFIG"]) { if (!process.env["KUBECONFIG"]) {
core.warning('KUBECONFIG env is not explicitly set. Ensure cluster context is set by using k8s-set-context / aks-set-context action.'); core.warning('KUBECONFIG env is not explicitly set. Ensure cluster context is set by using k8s-set-context / aks-set-context action.');
} }
} }
function run() { function run() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
checkClusterContext(); checkClusterContext();
yield setKubectlPath(); yield setKubectlPath();
let manifestsInput = core.getInput('manifests'); let manifestsInput = core.getInput('manifests');
if (!manifestsInput) { if (!manifestsInput) {
core.setFailed('No manifests supplied to deploy'); core.setFailed('No manifests supplied to deploy');
return; return;
} }
let namespace = core.getInput('namespace'); let namespace = core.getInput('namespace');
if (!namespace) { if (!namespace) {
namespace = 'default'; namespace = 'default';
} }
let action = core.getInput('action'); let action = core.getInput('action');
let manifests = manifestsInput.split(/[\n,;]+/).filter(manifest => manifest.trim().length > 0); let manifests = manifestsInput.split('\n');
if (manifests.length > 0) { if (action === 'deploy') {
manifests = manifests.map(manifest => { let strategy = core.getInput('strategy');
return manifest.trim(); console.log("strategy: ", strategy);
}); yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy);
} }
if (action === 'deploy') { else if (action === 'promote') {
let strategy = core.getInput('strategy'); yield promote_1.promote();
console.log("strategy: ", strategy); }
yield deployment_helper_1.deploy(new kubectl_object_model_1.Kubectl(kubectlPath, namespace), manifests, strategy); else if (action === 'reject') {
} yield reject_1.reject();
else if (action === 'promote') { }
yield promote_1.promote(true); else {
} core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject');
else if (action === 'reject') { }
yield reject_1.reject(true); });
} }
else { exports.run = run;
core.setFailed('Not a valid action. The allowed actions are deploy, promote, reject'); run().catch(core.setFailed);
}
});
}
exports.run = run;
run().catch(core.setFailed);
+78 -78
View File
@@ -1,78 +1,78 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.writeManifestToFile = exports.writeObjectsToFile = exports.assertFileExists = exports.ensureDirExists = exports.getNewUserDirPath = exports.getTempDirectory = void 0; exports.writeManifestToFile = exports.writeObjectsToFile = exports.assertFileExists = exports.ensureDirExists = exports.getNewUserDirPath = exports.getTempDirectory = void 0;
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const core = require("@actions/core"); const core = require("@actions/core");
const os = require("os"); const os = require("os");
function getTempDirectory() { function getTempDirectory() {
return process.env['runner.tempDirectory'] || os.tmpdir(); return process.env['runner.tempDirectory'] || os.tmpdir();
} }
exports.getTempDirectory = getTempDirectory; exports.getTempDirectory = getTempDirectory;
function getNewUserDirPath() { function getNewUserDirPath() {
let userDir = path.join(getTempDirectory(), 'kubectlTask'); let userDir = path.join(getTempDirectory(), 'kubectlTask');
ensureDirExists(userDir); ensureDirExists(userDir);
userDir = path.join(userDir, getCurrentTime().toString()); userDir = path.join(userDir, getCurrentTime().toString());
ensureDirExists(userDir); ensureDirExists(userDir);
return userDir; return userDir;
} }
exports.getNewUserDirPath = getNewUserDirPath; exports.getNewUserDirPath = getNewUserDirPath;
function ensureDirExists(dirPath) { function ensureDirExists(dirPath) {
if (!fs.existsSync(dirPath)) { if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath); fs.mkdirSync(dirPath);
} }
} }
exports.ensureDirExists = ensureDirExists; exports.ensureDirExists = ensureDirExists;
function assertFileExists(path) { function assertFileExists(path) {
if (!fs.existsSync(path)) { if (!fs.existsSync(path)) {
core.error(`FileNotFoundException : ${path}`); core.error(`FileNotFoundException : ${path}`);
throw new Error(`FileNotFoundException: ${path}`); throw new Error(`FileNotFoundException: ${path}`);
} }
} }
exports.assertFileExists = assertFileExists; exports.assertFileExists = assertFileExists;
function writeObjectsToFile(inputObjects) { function writeObjectsToFile(inputObjects) {
const newFilePaths = []; const newFilePaths = [];
if (!!inputObjects) { if (!!inputObjects) {
inputObjects.forEach((inputObject) => { inputObjects.forEach((inputObject) => {
try { try {
const inputObjectString = JSON.stringify(inputObject); const inputObjectString = JSON.stringify(inputObject);
if (!!inputObject.kind && !!inputObject.metadata && !!inputObject.metadata.name) { if (!!inputObject.kind && !!inputObject.metadata && !!inputObject.metadata.name) {
const fileName = getManifestFileName(inputObject.kind, inputObject.metadata.name); const fileName = getManifestFileName(inputObject.kind, inputObject.metadata.name);
fs.writeFileSync(path.join(fileName), inputObjectString); fs.writeFileSync(path.join(fileName), inputObjectString);
newFilePaths.push(fileName); newFilePaths.push(fileName);
} }
else { else {
core.debug('Input object is not proper K8s resource object. Object: ' + inputObjectString); core.debug('Input object is not proper K8s resource object. Object: ' + inputObjectString);
} }
} }
catch (ex) { catch (ex) {
core.debug('Exception occurred while writing object to file : ' + inputObject + ' . Exception: ' + ex); core.debug('Exception occurred while writing object to file : ' + inputObject + ' . Exception: ' + ex);
} }
}); });
} }
return newFilePaths; return newFilePaths;
} }
exports.writeObjectsToFile = writeObjectsToFile; exports.writeObjectsToFile = writeObjectsToFile;
function writeManifestToFile(inputObjectString, kind, name) { function writeManifestToFile(inputObjectString, kind, name) {
if (inputObjectString) { if (inputObjectString) {
try { try {
const fileName = getManifestFileName(kind, name); const fileName = getManifestFileName(kind, name);
fs.writeFileSync(path.join(fileName), inputObjectString); fs.writeFileSync(path.join(fileName), inputObjectString);
return fileName; return fileName;
} }
catch (ex) { catch (ex) {
core.debug('Exception occurred while writing object to file : ' + inputObjectString + ' . Exception: ' + ex); core.debug('Exception occurred while writing object to file : ' + inputObjectString + ' . Exception: ' + ex);
} }
} }
return ''; return '';
} }
exports.writeManifestToFile = writeManifestToFile; exports.writeManifestToFile = writeManifestToFile;
function getManifestFileName(kind, name) { function getManifestFileName(kind, name) {
const filePath = kind + '_' + name + '_' + getCurrentTime().toString(); const filePath = kind + '_' + name + '_' + getCurrentTime().toString();
const tempDirectory = getTempDirectory(); const tempDirectory = getTempDirectory();
const fileName = path.join(tempDirectory, path.basename(filePath)); const fileName = path.join(tempDirectory, path.basename(filePath));
return fileName; return fileName;
} }
function getCurrentTime() { function getCurrentTime() {
return new Date().getTime(); return new Date().getTime();
} }
+111
View File
@@ -0,0 +1,111 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sleepFor = exports.sendRequest = exports.WebRequestOptions = exports.WebResponse = exports.WebRequest = exports.StatusCodes = void 0;
// Taken from https://github.com/Azure/aks-set-context/blob/master/src/client.ts
const util = require("util");
const fs = require("fs");
const httpClient = require("typed-rest-client/HttpClient");
const core = require("@actions/core");
var httpCallbackClient = new httpClient.HttpClient('GITHUB_RUNNER', null, {});
var StatusCodes;
(function (StatusCodes) {
StatusCodes[StatusCodes["OK"] = 200] = "OK";
StatusCodes[StatusCodes["CREATED"] = 201] = "CREATED";
StatusCodes[StatusCodes["ACCEPTED"] = 202] = "ACCEPTED";
StatusCodes[StatusCodes["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
StatusCodes[StatusCodes["NOT_FOUND"] = 404] = "NOT_FOUND";
StatusCodes[StatusCodes["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
StatusCodes[StatusCodes["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
})(StatusCodes = exports.StatusCodes || (exports.StatusCodes = {}));
class WebRequest {
}
exports.WebRequest = WebRequest;
class WebResponse {
}
exports.WebResponse = WebResponse;
class WebRequestOptions {
}
exports.WebRequestOptions = WebRequestOptions;
function sendRequest(request, options) {
return __awaiter(this, void 0, void 0, function* () {
let i = 0;
let retryCount = options && options.retryCount ? options.retryCount : 5;
let retryIntervalInSeconds = options && options.retryIntervalInSeconds ? options.retryIntervalInSeconds : 2;
let retriableErrorCodes = options && options.retriableErrorCodes ? options.retriableErrorCodes : ["ETIMEDOUT", "ECONNRESET", "ENOTFOUND", "ESOCKETTIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "EPIPE", "EA_AGAIN"];
let retriableStatusCodes = options && options.retriableStatusCodes ? options.retriableStatusCodes : [408, 409, 500, 502, 503, 504];
let timeToWait = retryIntervalInSeconds;
while (true) {
try {
if (request.body && typeof (request.body) !== 'string' && !request.body["readable"]) {
request.body = fs.createReadStream(request.body["path"]);
}
let response = yield sendRequestInternal(request);
if (retriableStatusCodes.indexOf(response.statusCode) != -1 && ++i < retryCount) {
core.debug(util.format("Encountered a retriable status code: %s. Message: '%s'.", response.statusCode, response.statusMessage));
yield sleepFor(timeToWait);
timeToWait = timeToWait * retryIntervalInSeconds + retryIntervalInSeconds;
continue;
}
return response;
}
catch (error) {
if (retriableErrorCodes.indexOf(error.code) != -1 && ++i < retryCount) {
core.debug(util.format("Encountered a retriable error:%s. Message: %s.", error.code, error.message));
yield sleepFor(timeToWait);
timeToWait = timeToWait * retryIntervalInSeconds + retryIntervalInSeconds;
}
else {
if (error.code) {
core.debug("error code =" + error.code);
}
throw error;
}
}
}
});
}
exports.sendRequest = sendRequest;
function sleepFor(sleepDurationInSeconds) {
return new Promise((resolve, reject) => {
setTimeout(resolve, sleepDurationInSeconds * 1000);
});
}
exports.sleepFor = sleepFor;
function sendRequestInternal(request) {
return __awaiter(this, void 0, void 0, function* () {
core.debug(util.format("[%s]%s", request.method, request.uri));
var response = yield httpCallbackClient.request(request.method, request.uri, request.body, request.headers);
return yield toWebResponse(response);
});
}
function toWebResponse(response) {
return __awaiter(this, void 0, void 0, function* () {
var res = new WebResponse();
if (response) {
res.statusCode = response.message.statusCode;
res.statusMessage = response.message.statusMessage;
res.headers = response.message.headers;
var body = yield response.readBody();
if (body) {
try {
res.body = JSON.parse(body);
}
catch (error) {
core.debug("Could not parse response: " + JSON.stringify(error));
core.debug("Response: " + JSON.stringify(res.body));
res.body = body;
}
}
}
return res;
});
}
+84 -84
View File
@@ -1,84 +1,84 @@
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getTrafficSplitAPIVersion = exports.downloadKubectl = exports.getStableKubectlVersion = exports.getkubectlDownloadURL = void 0; exports.getTrafficSplitAPIVersion = exports.downloadKubectl = exports.getStableKubectlVersion = exports.getkubectlDownloadURL = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const fs = require("fs"); const fs = require("fs");
const os = require("os"); const os = require("os");
const path = require("path"); const path = require("path");
const toolCache = require("@actions/tool-cache"); const toolCache = require("@actions/tool-cache");
const util = require("util"); const util = require("util");
const kubectlToolName = 'kubectl'; const kubectlToolName = 'kubectl';
const stableKubectlVersion = 'v1.15.0'; const stableKubectlVersion = 'v1.15.0';
const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt'; const stableVersionUrl = 'https://storage.googleapis.com/kubernetes-release/release/stable.txt';
const trafficSplitAPIVersionPrefix = 'split.smi-spec.io'; const trafficSplitAPIVersionPrefix = 'split.smi-spec.io';
function getExecutableExtension() { function getExecutableExtension() {
if (os.type().match(/^Win/)) { if (os.type().match(/^Win/)) {
return '.exe'; return '.exe';
} }
return ''; return '';
} }
function getkubectlDownloadURL(version) { function getkubectlDownloadURL(version) {
switch (os.type()) { switch (os.type()) {
case 'Linux': case 'Linux':
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/amd64/kubectl', version); return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/amd64/kubectl', version);
case 'Darwin': case 'Darwin':
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/amd64/kubectl', version); return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/darwin/amd64/kubectl', version);
case 'Windows_NT': case 'Windows_NT':
default: default:
return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/amd64/kubectl.exe', version); return util.format('https://storage.googleapis.com/kubernetes-release/release/%s/bin/windows/amd64/kubectl.exe', version);
} }
} }
exports.getkubectlDownloadURL = getkubectlDownloadURL; exports.getkubectlDownloadURL = getkubectlDownloadURL;
function getStableKubectlVersion() { function getStableKubectlVersion() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
return toolCache.downloadTool(stableVersionUrl).then((downloadPath) => { return toolCache.downloadTool(stableVersionUrl).then((downloadPath) => {
let version = fs.readFileSync(downloadPath, 'utf8').toString().trim(); let version = fs.readFileSync(downloadPath, 'utf8').toString().trim();
if (!version) { if (!version) {
version = stableKubectlVersion; version = stableKubectlVersion;
} }
return version; return version;
}, (error) => { }, (error) => {
core.debug(error); core.debug(error);
core.warning('GetStableVersionFailed'); core.warning('GetStableVersionFailed');
return stableKubectlVersion; return stableKubectlVersion;
}); });
}); });
} }
exports.getStableKubectlVersion = getStableKubectlVersion; exports.getStableKubectlVersion = getStableKubectlVersion;
function downloadKubectl(version) { function downloadKubectl(version) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let cachedToolpath = toolCache.find(kubectlToolName, version); let cachedToolpath = toolCache.find(kubectlToolName, version);
let kubectlDownloadPath = ''; let kubectlDownloadPath = '';
if (!cachedToolpath) { if (!cachedToolpath) {
try { try {
kubectlDownloadPath = yield toolCache.downloadTool(getkubectlDownloadURL(version)); kubectlDownloadPath = yield toolCache.downloadTool(getkubectlDownloadURL(version));
} }
catch (exception) { catch (exception) {
throw new Error('DownloadKubectlFailed'); throw new Error('DownloadKubectlFailed');
} }
cachedToolpath = yield toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version); cachedToolpath = yield toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version);
} }
const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension()); const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension());
fs.chmodSync(kubectlPath, '777'); fs.chmodSync(kubectlPath, '777');
return kubectlPath; return kubectlPath;
}); });
} }
exports.downloadKubectl = downloadKubectl; exports.downloadKubectl = downloadKubectl;
function getTrafficSplitAPIVersion(kubectl) { function getTrafficSplitAPIVersion(kubectl) {
const result = kubectl.executeCommand('api-versions'); const result = kubectl.executeCommand('api-versions');
const trafficSplitAPIVersion = result.stdout.split('\n').find(version => version.startsWith(trafficSplitAPIVersionPrefix)); const trafficSplitAPIVersion = result.stdout.split('\n').find(version => version.startsWith(trafficSplitAPIVersionPrefix));
if (!trafficSplitAPIVersion) { if (!trafficSplitAPIVersion) {
throw new Error('UnableToCreateTrafficSplitManifestFile'); throw new Error('UnableToCreateTrafficSplitManifestFile');
} }
return trafficSplitAPIVersion; return trafficSplitAPIVersion;
} }
exports.getTrafficSplitAPIVersion = getTrafficSplitAPIVersion; exports.getTrafficSplitAPIVersion = getTrafficSplitAPIVersion;
+158 -158
View File
@@ -1,158 +1,158 @@
'use strict'; 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.checkPodStatus = exports.checkManifestStability = void 0; exports.checkPodStatus = exports.checkManifestStability = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const utils = require("./utility"); const utils = require("./utility");
const KubernetesConstants = require("../constants"); const KubernetesConstants = require("../constants");
function checkManifestStability(kubectl, resources) { function checkManifestStability(kubectl, resources) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let rolloutStatusHasErrors = false; let rolloutStatusHasErrors = false;
const numberOfResources = resources.length; const numberOfResources = resources.length;
for (let i = 0; i < numberOfResources; i++) { for (let i = 0; i < numberOfResources; i++) {
const resource = resources[i]; const resource = resources[i];
if (KubernetesConstants.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) { if (KubernetesConstants.workloadTypesWithRolloutStatus.indexOf(resource.type.toLowerCase()) >= 0) {
try { try {
var result = kubectl.checkRolloutStatus(resource.type, resource.name); var result = kubectl.checkRolloutStatus(resource.type, resource.name);
utils.checkForErrors([result]); utils.checkForErrors([result]);
} }
catch (ex) { catch (ex) {
core.error(ex); core.error(ex);
kubectl.describe(resource.type, resource.name); kubectl.describe(resource.type, resource.name);
rolloutStatusHasErrors = true; rolloutStatusHasErrors = true;
} }
} }
if (utils.isEqual(resource.type, KubernetesConstants.KubernetesWorkload.pod, true)) { if (utils.isEqual(resource.type, KubernetesConstants.KubernetesWorkload.pod, true)) {
try { try {
yield checkPodStatus(kubectl, resource.name); yield checkPodStatus(kubectl, resource.name);
} }
catch (ex) { catch (ex) {
core.warning(`CouldNotDeterminePodStatus ${JSON.stringify(ex)}`); core.warning(`CouldNotDeterminePodStatus ${JSON.stringify(ex)}`);
kubectl.describe(resource.type, resource.name); kubectl.describe(resource.type, resource.name);
} }
} }
if (utils.isEqual(resource.type, KubernetesConstants.DiscoveryAndLoadBalancerResource.service, true)) { if (utils.isEqual(resource.type, KubernetesConstants.DiscoveryAndLoadBalancerResource.service, true)) {
try { try {
const service = getService(kubectl, resource.name); const service = getService(kubectl, resource.name);
const spec = service.spec; const spec = service.spec;
const status = service.status; const status = service.status;
if (utils.isEqual(spec.type, KubernetesConstants.ServiceTypes.loadBalancer, true)) { if (utils.isEqual(spec.type, KubernetesConstants.ServiceTypes.loadBalancer, true)) {
if (!isLoadBalancerIPAssigned(status)) { if (!isLoadBalancerIPAssigned(status)) {
yield waitForServiceExternalIPAssignment(kubectl, resource.name); yield waitForServiceExternalIPAssignment(kubectl, resource.name);
} }
else { else {
console.log('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip); console.log('ServiceExternalIP', resource.name, status.loadBalancer.ingress[0].ip);
} }
} }
} }
catch (ex) { catch (ex) {
core.warning(`CouldNotDetermineServiceStatus of: ${resource.name} Error: ${JSON.stringify(ex)}`); core.warning(`CouldNotDetermineServiceStatus of: ${resource.name} Error: ${JSON.stringify(ex)}`);
kubectl.describe(resource.type, resource.name); kubectl.describe(resource.type, resource.name);
} }
} }
} }
if (rolloutStatusHasErrors) { if (rolloutStatusHasErrors) {
throw new Error('RolloutStatusTimedout'); throw new Error('RolloutStatusTimedout');
} }
}); });
} }
exports.checkManifestStability = checkManifestStability; exports.checkManifestStability = checkManifestStability;
function checkPodStatus(kubectl, podName) { function checkPodStatus(kubectl, podName) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const sleepTimeout = 10 * 1000; // 10 seconds const sleepTimeout = 10 * 1000; // 10 seconds
const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout const iterations = 60; // 60 * 10 seconds timeout = 10 minutes max timeout
let podStatus; let podStatus;
let kubectlDescribeNeeded = false; let kubectlDescribeNeeded = false;
for (let i = 0; i < iterations; i++) { for (let i = 0; i < iterations; i++) {
yield utils.sleep(sleepTimeout); yield utils.sleep(sleepTimeout);
core.debug(`Polling for pod status: ${podName}`); core.debug(`Polling for pod status: ${podName}`);
podStatus = getPodStatus(kubectl, podName); podStatus = getPodStatus(kubectl, podName);
if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') { if (podStatus.phase && podStatus.phase !== 'Pending' && podStatus.phase !== 'Unknown') {
break; break;
} }
} }
podStatus = getPodStatus(kubectl, podName); podStatus = getPodStatus(kubectl, podName);
switch (podStatus.phase) { switch (podStatus.phase) {
case 'Succeeded': case 'Succeeded':
case 'Running': case 'Running':
if (isPodReady(podStatus)) { if (isPodReady(podStatus)) {
console.log(`pod/${podName} is successfully rolled out`); console.log(`pod/${podName} is successfully rolled out`);
} }
else { else {
kubectlDescribeNeeded = true; kubectlDescribeNeeded = true;
} }
break; break;
case 'Pending': case 'Pending':
if (!isPodReady(podStatus)) { if (!isPodReady(podStatus)) {
core.warning(`pod/${podName} rollout status check timedout`); core.warning(`pod/${podName} rollout status check timedout`);
kubectlDescribeNeeded = true; kubectlDescribeNeeded = true;
} }
break; break;
case 'Failed': case 'Failed':
core.error(`pod/${podName} rollout failed`); core.error(`pod/${podName} rollout failed`);
kubectlDescribeNeeded = true; kubectlDescribeNeeded = true;
break; break;
default: default:
core.warning(`pod/${podName} rollout status: ${podStatus.phase}`); core.warning(`pod/${podName} rollout status: ${podStatus.phase}`);
} }
if (kubectlDescribeNeeded) { if (kubectlDescribeNeeded) {
kubectl.describe('pod', podName); kubectl.describe('pod', podName);
} }
}); });
} }
exports.checkPodStatus = checkPodStatus; exports.checkPodStatus = checkPodStatus;
function getPodStatus(kubectl, podName) { function getPodStatus(kubectl, podName) {
const podResult = kubectl.getResource('pod', podName); const podResult = kubectl.getResource('pod', podName);
utils.checkForErrors([podResult]); utils.checkForErrors([podResult]);
const podStatus = JSON.parse(podResult.stdout).status; const podStatus = JSON.parse(podResult.stdout).status;
core.debug(`Pod Status: ${JSON.stringify(podStatus)}`); core.debug(`Pod Status: ${JSON.stringify(podStatus)}`);
return podStatus; return podStatus;
} }
function isPodReady(podStatus) { function isPodReady(podStatus) {
let allContainersAreReady = true; let allContainersAreReady = true;
podStatus.containerStatuses.forEach(container => { podStatus.containerStatuses.forEach(container => {
if (container.ready === false) { if (container.ready === false) {
console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`); console.log(`'${container.name}' status: ${JSON.stringify(container.state)}`);
allContainersAreReady = false; allContainersAreReady = false;
} }
}); });
if (!allContainersAreReady) { if (!allContainersAreReady) {
core.warning('AllContainersNotInReadyState'); core.warning('AllContainersNotInReadyState');
} }
return allContainersAreReady; return allContainersAreReady;
} }
function getService(kubectl, serviceName) { function getService(kubectl, serviceName) {
const serviceResult = kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.service, serviceName); const serviceResult = kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.service, serviceName);
utils.checkForErrors([serviceResult]); utils.checkForErrors([serviceResult]);
return JSON.parse(serviceResult.stdout); return JSON.parse(serviceResult.stdout);
} }
function waitForServiceExternalIPAssignment(kubectl, serviceName) { function waitForServiceExternalIPAssignment(kubectl, serviceName) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const sleepTimeout = 10 * 1000; // 10 seconds const sleepTimeout = 10 * 1000; // 10 seconds
const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout const iterations = 18; // 18 * 10 seconds timeout = 3 minutes max timeout
for (let i = 0; i < iterations; i++) { for (let i = 0; i < iterations; i++) {
console.log(`waitForServiceIpAssignment : ${serviceName}`); console.log(`waitForServiceIpAssignment : ${serviceName}`);
yield utils.sleep(sleepTimeout); yield utils.sleep(sleepTimeout);
let status = (getService(kubectl, serviceName)).status; let status = (getService(kubectl, serviceName)).status;
if (isLoadBalancerIPAssigned(status)) { if (isLoadBalancerIPAssigned(status)) {
console.log('ServiceExternalIP', serviceName, status.loadBalancer.ingress[0].ip); console.log('ServiceExternalIP', serviceName, status.loadBalancer.ingress[0].ip);
return; return;
} }
} }
core.warning(`waitForServiceIpAssignmentTimedOut ${serviceName}`); core.warning(`waitForServiceIpAssignmentTimedOut ${serviceName}`);
}); });
} }
function isLoadBalancerIPAssigned(status) { function isLoadBalancerIPAssigned(status) {
if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) { if (status && status.loadBalancer && status.loadBalancer.ingress && status.loadBalancer.ingress.length > 0) {
return true; return true;
} }
return false; return false;
} }
+283 -236
View File
@@ -1,236 +1,283 @@
'use strict'; 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.isWorkloadEntity = exports.updateImagePullSecrets = exports.updateContainerImagesInManifestFiles = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0; exports.isWorkloadEntity = exports.getUpdatedManifestFiles = exports.updateImagePullSecrets = exports.substituteImageNameInSpecFile = exports.getDeleteCmdArgs = exports.createKubectlArgs = exports.getKubectl = exports.getManifestFiles = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const kubectlutility = require("./kubectl-util"); const fs = require("fs");
const io = require("@actions/io"); const yaml = require("js-yaml");
const utility_1 = require("./utility"); const path = require("path");
function getManifestFiles(manifestFilePaths) { const kubectlutility = require("./kubectl-util");
if (!manifestFilePaths) { const io = require("@actions/io");
core.debug('file input is not present'); const utility_1 = require("./utility");
return null; const fileHelper = require("./files-helper");
} const KubernetesObjectUtility = require("./resource-object-utility");
return manifestFilePaths; const TaskInputParameters = require("../input-parameters");
} function getManifestFiles(manifestFilePaths) {
exports.getManifestFiles = getManifestFiles; if (!manifestFilePaths) {
function getKubectl() { core.debug('file input is not present');
return __awaiter(this, void 0, void 0, function* () { return null;
try { }
return Promise.resolve(io.which('kubectl', true)); return manifestFilePaths;
} }
catch (ex) { exports.getManifestFiles = getManifestFiles;
return kubectlutility.downloadKubectl(yield kubectlutility.getStableKubectlVersion()); function getKubectl() {
} return __awaiter(this, void 0, void 0, function* () {
}); try {
} return Promise.resolve(io.which('kubectl', true));
exports.getKubectl = getKubectl; }
function createKubectlArgs(kinds, names) { catch (ex) {
let args = ''; return kubectlutility.downloadKubectl(yield kubectlutility.getStableKubectlVersion());
if (!!kinds && kinds.size > 0) { }
args = args + createInlineArray(Array.from(kinds.values())); });
} }
if (!!names && names.size > 0) { exports.getKubectl = getKubectl;
args = args + ' ' + Array.from(names.values()).join(' '); function createKubectlArgs(kinds, names) {
} let args = '';
return args; if (!!kinds && kinds.size > 0) {
} args = args + createInlineArray(Array.from(kinds.values()));
exports.createKubectlArgs = createKubectlArgs; }
function getDeleteCmdArgs(argsPrefix, inputArgs) { if (!!names && names.size > 0) {
let args = ''; args = args + ' ' + Array.from(names.values()).join(' ');
if (!!argsPrefix && argsPrefix.length > 0) { }
args = argsPrefix; return args;
} }
if (!!inputArgs && inputArgs.length > 0) { exports.createKubectlArgs = createKubectlArgs;
if (args.length > 0) { function getDeleteCmdArgs(argsPrefix, inputArgs) {
args = args + ' '; let args = '';
} if (!!argsPrefix && argsPrefix.length > 0) {
args = args + inputArgs; args = argsPrefix;
} }
return args; if (!!inputArgs && inputArgs.length > 0) {
} if (args.length > 0) {
exports.getDeleteCmdArgs = getDeleteCmdArgs; args = args + ' ';
/* }
For example, args = args + inputArgs;
currentString: `image: "example/example-image"` }
imageName: `example/example-image` return args;
imageNameWithNewTag: `example/example-image:identifiertag` }
exports.getDeleteCmdArgs = getDeleteCmdArgs;
This substituteImageNameInSpecFile function would return /*
return Value: `image: "example/example-image:identifiertag"` For example,
*/ currentString: `image: "example/example-image"`
function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) { imageName: `example/example-image`
if (currentString.indexOf(imageName) < 0) { imageNameWithNewTag: `example/example-image:identifiertag`
core.debug(`No occurence of replacement token: ${imageName} found`);
return currentString; This substituteImageNameInSpecFile function would return
} return Value: `image: "example/example-image:identifiertag"`
return currentString.split('\n').reduce((acc, line) => { */
const imageKeyword = line.match(/^ *image:/); function substituteImageNameInSpecFile(currentString, imageName, imageNameWithNewTag) {
if (imageKeyword) { if (currentString.indexOf(imageName) < 0) {
let [currentImageName, currentImageTag] = line core.debug(`No occurence of replacement token: ${imageName} found`);
.substring(imageKeyword[0].length) // consume the line from keyword onwards return currentString;
.trim() }
.replace(/[',"]/g, '') // replace allowed quotes with nothing return currentString.split('\n').reduce((acc, line) => {
.split(':'); const imageKeyword = line.match(/^ *image:/);
if (!currentImageTag && currentImageName.indexOf(' ') > 0) { if (imageKeyword) {
currentImageName = currentImageName.split(' ')[0]; // Stripping off comments let [currentImageName, currentImageTag] = line
} .substring(imageKeyword[0].length) // consume the line from keyword onwards
if (currentImageName === imageName) { .trim()
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`; .replace(/[',"]/g, '') // replace allowed quotes with nothing
} .split(':');
} if (!currentImageTag && currentImageName.indexOf(' ') > 0) {
return acc + line + '\n'; currentImageName = currentImageName.split(' ')[0]; // Stripping off comments
}, ''); }
} if (currentImageName === imageName) {
exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile; return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
function createInlineArray(str) { }
if (typeof str === 'string') { }
return str; return acc + line + '\n';
} }, '');
return str.join(','); }
} exports.substituteImageNameInSpecFile = substituteImageNameInSpecFile;
function getImagePullSecrets(inputObject) { function createInlineArray(str) {
if (!inputObject || !inputObject.spec) { if (typeof str === 'string') {
return; return str;
} }
if (utility_1.isEqual(inputObject.kind, 'pod') return str.join(',');
&& inputObject }
&& inputObject.spec function getImagePullSecrets(inputObject) {
&& inputObject.spec.imagePullSecrets) { if (!inputObject || !inputObject.spec) {
return inputObject.spec.imagePullSecrets; return;
} }
else if (utility_1.isEqual(inputObject.kind, 'cronjob') if (utility_1.isEqual(inputObject.kind, 'pod')
&& inputObject && inputObject
&& inputObject.spec && inputObject.spec
&& inputObject.spec.jobTemplate && inputObject.spec.imagePullSecrets) {
&& inputObject.spec.jobTemplate.spec return inputObject.spec.imagePullSecrets;
&& inputObject.spec.jobTemplate.spec.template }
&& inputObject.spec.jobTemplate.spec.template.spec else if (utility_1.isEqual(inputObject.kind, 'cronjob')
&& inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets) { && inputObject
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets; && inputObject.spec
} && inputObject.spec.jobTemplate
else if (inputObject && inputObject.spec.jobTemplate.spec
&& inputObject.spec && inputObject.spec.jobTemplate.spec.template
&& inputObject.spec.template && inputObject.spec.jobTemplate.spec.template.spec
&& inputObject.spec.template.spec && inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets) {
&& inputObject.spec.template.spec.imagePullSecrets) { return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
return inputObject.spec.template.spec.imagePullSecrets; }
} else if (inputObject
} && inputObject.spec
function setImagePullSecrets(inputObject, newImagePullSecrets) { && inputObject.spec.template
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { && inputObject.spec.template.spec
return; && inputObject.spec.template.spec.imagePullSecrets) {
} return inputObject.spec.template.spec.imagePullSecrets;
if (utility_1.isEqual(inputObject.kind, 'pod')) { }
if (inputObject }
&& inputObject.spec) { function setImagePullSecrets(inputObject, newImagePullSecrets) {
if (newImagePullSecrets.length > 0) { if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
inputObject.spec.imagePullSecrets = newImagePullSecrets; return;
} }
else { if (utility_1.isEqual(inputObject.kind, 'pod')) {
delete inputObject.spec.imagePullSecrets; if (inputObject
} && inputObject.spec) {
} if (newImagePullSecrets.length > 0) {
} inputObject.spec.imagePullSecrets = newImagePullSecrets;
else if (utility_1.isEqual(inputObject.kind, 'cronjob')) { }
if (inputObject else {
&& inputObject.spec delete inputObject.spec.imagePullSecrets;
&& inputObject.spec.jobTemplate }
&& inputObject.spec.jobTemplate.spec }
&& inputObject.spec.jobTemplate.spec.template }
&& inputObject.spec.jobTemplate.spec.template.spec) { else if (utility_1.isEqual(inputObject.kind, 'cronjob')) {
if (newImagePullSecrets.length > 0) { if (inputObject
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets; && inputObject.spec
} && inputObject.spec.jobTemplate
else { && inputObject.spec.jobTemplate.spec
delete inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets; && inputObject.spec.jobTemplate.spec.template
} && inputObject.spec.jobTemplate.spec.template.spec) {
} if (newImagePullSecrets.length > 0) {
} inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
else if (!!inputObject.spec.template && !!inputObject.spec.template.spec) { }
if (inputObject else {
&& inputObject.spec delete inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
&& inputObject.spec.template }
&& inputObject.spec.template.spec) { }
if (newImagePullSecrets.length > 0) { }
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets; else if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
} if (inputObject
else { && inputObject.spec
delete inputObject.spec.template.spec.imagePullSecrets; && inputObject.spec.template
} && inputObject.spec.template.spec) {
} if (newImagePullSecrets.length > 0) {
} inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
} }
function substituteImageNameInSpecContent(currentString, imageName, imageNameWithNewTag) { else {
if (currentString.indexOf(imageName) < 0) { delete inputObject.spec.template.spec.imagePullSecrets;
core.debug(`No occurence of replacement token: ${imageName} found`); }
return currentString; }
} }
return currentString.split('\n').reduce((acc, line) => { }
const imageKeyword = line.match(/^ *image:/); function substituteImageNameInSpecContent(currentString, imageName, imageNameWithNewTag) {
if (imageKeyword) { if (currentString.indexOf(imageName) < 0) {
const [currentImageName, currentImageTag] = line core.debug(`No occurence of replacement token: ${imageName} found`);
.substring(imageKeyword[0].length) // consume the line from keyword onwards return currentString;
.trim() }
.replace(/[',"]/g, '') // replace allowed quotes with nothing return currentString.split('\n').reduce((acc, line) => {
.split(':'); const imageKeyword = line.match(/^ *image:/);
if (currentImageName === imageName) { if (imageKeyword) {
return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`; const [currentImageName, currentImageTag] = line
} .substring(imageKeyword[0].length) // consume the line from keyword onwards
} .trim()
return acc + line + '\n'; .replace(/[',"]/g, '') // replace allowed quotes with nothing
}, ''); .split(':');
} if (currentImageName === imageName) {
function updateContainerImagesInManifestFiles(contents, containers) { return acc + `${imageKeyword[0]} ${imageNameWithNewTag}\n`;
if (!!containers && containers.length > 0) { }
containers.forEach((container) => { }
let imageName = container.split(':')[0]; return acc + line + '\n';
if (imageName.indexOf('@') > 0) { }, '');
imageName = imageName.split('@')[0]; }
} function updateContainerImagesInManifestFiles(filePaths, containers) {
if (contents.indexOf(imageName) > 0) { if (!!containers && containers.length > 0) {
contents = substituteImageNameInSpecContent(contents, imageName, container); const newFilePaths = [];
} const tempDirectory = fileHelper.getTempDirectory();
}); filePaths.forEach((filePath) => {
} let contents = fs.readFileSync(filePath).toString();
return contents; containers.forEach((container) => {
} let imageName = container.split(':')[0];
exports.updateContainerImagesInManifestFiles = updateContainerImagesInManifestFiles; if (imageName.indexOf('@') > 0) {
function updateImagePullSecrets(inputObject, newImagePullSecrets) { imageName = imageName.split('@')[0];
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { }
return; if (contents.indexOf(imageName) > 0) {
} contents = substituteImageNameInSpecFile(contents, imageName, container);
let newImagePullSecretsObjects; }
if (newImagePullSecrets.length > 0) { });
newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return !!x ? { 'name': x } : null; }); const fileName = path.join(tempDirectory, path.basename(filePath));
} fs.writeFileSync(path.join(fileName), contents);
else { newFilePaths.push(fileName);
newImagePullSecretsObjects = []; });
} return newFilePaths;
let existingImagePullSecretObjects = getImagePullSecrets(inputObject); }
if (!existingImagePullSecretObjects) { return filePaths;
existingImagePullSecretObjects = new Array(); }
} function updateImagePullSecrets(inputObject, newImagePullSecrets) {
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects); if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
setImagePullSecrets(inputObject, existingImagePullSecretObjects); return;
} }
exports.updateImagePullSecrets = updateImagePullSecrets; let newImagePullSecretsObjects;
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob']; if (newImagePullSecrets.length > 0) {
function isWorkloadEntity(kind) { newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return !!x ? { 'name': x } : null; });
if (!kind) { }
core.debug('ResourceKindNotDefined'); else {
return false; newImagePullSecretsObjects = [];
} }
return workloadTypes.some((type) => { let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
return utility_1.isEqual(type, kind); if (!existingImagePullSecretObjects) {
}); existingImagePullSecretObjects = new Array();
} }
exports.isWorkloadEntity = isWorkloadEntity; existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
setImagePullSecrets(inputObject, existingImagePullSecretObjects);
}
exports.updateImagePullSecrets = updateImagePullSecrets;
function updateImagePullSecretsInManifestFiles(filePaths, imagePullSecrets) {
if (!!imagePullSecrets && imagePullSecrets.length > 0) {
const newObjectsList = [];
filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath).toString();
yaml.safeLoadAll(fileContents, function (inputObject) {
if (!!inputObject && !!inputObject.kind) {
const kind = inputObject.kind;
if (KubernetesObjectUtility.isWorkloadEntity(kind)) {
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false);
}
newObjectsList.push(inputObject);
}
});
});
core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList));
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList);
return newFilePaths;
}
return filePaths;
}
function getUpdatedManifestFiles(manifestFilePaths) {
let inputManifestFiles = getManifestFiles(manifestFilePaths);
if (!inputManifestFiles || inputManifestFiles.length === 0) {
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
}
// artifact substitution
inputManifestFiles = updateContainerImagesInManifestFiles(inputManifestFiles, TaskInputParameters.containers);
// imagePullSecrets addition
inputManifestFiles = updateImagePullSecretsInManifestFiles(inputManifestFiles, TaskInputParameters.imagePullSecrets);
return inputManifestFiles;
}
exports.getUpdatedManifestFiles = getUpdatedManifestFiles;
const workloadTypes = ['deployment', 'replicaset', 'daemonset', 'pod', 'statefulset', 'job', 'cronjob'];
function isWorkloadEntity(kind) {
if (!kind) {
core.debug('ResourceKindNotDefined');
return false;
}
return workloadTypes.some((type) => {
return utility_1.isEqual(type, kind);
});
}
exports.isWorkloadEntity = isWorkloadEntity;
+277 -324
View File
@@ -1,324 +1,277 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImageDetails = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0; exports.getResources = exports.updateSelectorLabels = exports.updateSpecLabels = exports.updateImagePullSecrets = exports.updateObjectAnnotations = exports.updateObjectLabels = exports.getReplicaCount = exports.isIngressEntity = exports.isServiceEntity = exports.isWorkloadEntity = exports.isDeploymentEntity = void 0;
const fs = require("fs"); const fs = require("fs");
const core = require("@actions/core"); const core = require("@actions/core");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const constants_1 = require("../constants"); const constants_1 = require("../constants");
const string_comparison_1 = require("./string-comparison"); const string_comparison_1 = require("./string-comparison");
function isDeploymentEntity(kind) { const INGRESS = "Ingress";
if (!kind) { function isDeploymentEntity(kind) {
throw ('ResourceKindNotDefined'); if (!kind) {
} throw ('ResourceKindNotDefined');
return constants_1.deploymentTypes.some((type) => { }
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); return constants_1.deploymentTypes.some((type) => {
}); return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
} });
exports.isDeploymentEntity = isDeploymentEntity; }
function isWorkloadEntity(kind) { exports.isDeploymentEntity = isDeploymentEntity;
if (!kind) { function isWorkloadEntity(kind) {
throw ('ResourceKindNotDefined'); if (!kind) {
} throw ('ResourceKindNotDefined');
return constants_1.workloadTypes.some((type) => { }
return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); return constants_1.workloadTypes.some((type) => {
}); return string_comparison_1.isEqual(type, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
} });
exports.isWorkloadEntity = isWorkloadEntity; }
function isServiceEntity(kind) { exports.isWorkloadEntity = isWorkloadEntity;
if (!kind) { function isServiceEntity(kind) {
throw ('ResourceKindNotDefined'); if (!kind) {
} throw ('ResourceKindNotDefined');
return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase); }
} return string_comparison_1.isEqual("Service", kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
exports.isServiceEntity = isServiceEntity; }
function getReplicaCount(inputObject) { exports.isServiceEntity = isServiceEntity;
if (!inputObject) { function isIngressEntity(kind) {
throw ('NullInputObject'); if (!kind) {
} throw ('ResourceKindNotDefined');
if (!inputObject.kind) { }
throw ('ResourceKindNotDefined'); return string_comparison_1.isEqual(INGRESS, kind, string_comparison_1.StringComparer.OrdinalIgnoreCase);
} }
const kind = inputObject.kind; exports.isIngressEntity = isIngressEntity;
if (!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { function getReplicaCount(inputObject) {
return inputObject.spec.replicas; if (!inputObject) {
} throw ('NullInputObject');
return 0; }
} if (!inputObject.kind) {
exports.getReplicaCount = getReplicaCount; throw ('ResourceKindNotDefined');
function updateObjectLabels(inputObject, newLabels, override) { }
if (!inputObject) { const kind = inputObject.kind;
throw ('NullInputObject'); if (!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
} return inputObject.spec.replicas;
if (!inputObject.metadata) { }
throw ('NullInputObjectMetadata'); return 0;
} }
if (!newLabels) { exports.getReplicaCount = getReplicaCount;
return; function updateObjectLabels(inputObject, newLabels, override) {
} if (!inputObject) {
if (override) { throw ('NullInputObject');
inputObject.metadata.labels = newLabels; }
} if (!inputObject.metadata) {
else { throw ('NullInputObjectMetadata');
let existingLabels = inputObject.metadata.labels; }
if (!existingLabels) { if (!newLabels) {
existingLabels = new Map(); return;
} }
Object.keys(newLabels).forEach(function (key) { if (override) {
existingLabels[key] = newLabels[key]; inputObject.metadata.labels = newLabels;
}); }
inputObject.metadata.labels = existingLabels; else {
} let existingLabels = inputObject.metadata.labels;
} if (!existingLabels) {
exports.updateObjectLabels = updateObjectLabels; existingLabels = new Map();
function updateObjectAnnotations(inputObject, newAnnotations, override) { }
if (!inputObject) { Object.keys(newLabels).forEach(function (key) {
throw ('NullInputObject'); existingLabels[key] = newLabels[key];
} });
if (!inputObject.metadata) { inputObject.metadata.labels = existingLabels;
throw ('NullInputObjectMetadata'); }
} }
if (!newAnnotations) { exports.updateObjectLabels = updateObjectLabels;
return; function updateObjectAnnotations(inputObject, newAnnotations, override) {
} if (!inputObject) {
if (override) { throw ('NullInputObject');
inputObject.metadata.annotations = newAnnotations; }
} if (!inputObject.metadata) {
else { throw ('NullInputObjectMetadata');
let existingAnnotations = inputObject.metadata.annotations; }
if (!existingAnnotations) { if (!newAnnotations) {
existingAnnotations = new Map(); return;
} }
Object.keys(newAnnotations).forEach(function (key) { if (override) {
existingAnnotations[key] = newAnnotations[key]; inputObject.metadata.annotations = newAnnotations;
}); }
inputObject.metadata.annotations = existingAnnotations; else {
} let existingAnnotations = inputObject.metadata.annotations;
} if (!existingAnnotations) {
exports.updateObjectAnnotations = updateObjectAnnotations; existingAnnotations = new Map();
function updateImagePullSecrets(inputObject, newImagePullSecrets, override) { }
if (!inputObject || !inputObject.spec || !newImagePullSecrets) { Object.keys(newAnnotations).forEach(function (key) {
return; existingAnnotations[key] = newAnnotations[key];
} });
const newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return { 'name': x }; }); inputObject.metadata.annotations = existingAnnotations;
let existingImagePullSecretObjects = getImagePullSecrets(inputObject); }
if (override) { }
existingImagePullSecretObjects = newImagePullSecretsObjects; exports.updateObjectAnnotations = updateObjectAnnotations;
} function updateImagePullSecrets(inputObject, newImagePullSecrets, override) {
else { if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
if (!existingImagePullSecretObjects) { return;
existingImagePullSecretObjects = new Array(); }
} const newImagePullSecretsObjects = Array.from(newImagePullSecrets, x => { return { 'name': x }; });
existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects); let existingImagePullSecretObjects = getImagePullSecrets(inputObject);
} if (override) {
setImagePullSecrets(inputObject, existingImagePullSecretObjects); existingImagePullSecretObjects = newImagePullSecretsObjects;
} }
exports.updateImagePullSecrets = updateImagePullSecrets; else {
function updateImageDetails(inputObject, containers) { if (!existingImagePullSecretObjects) {
if (!inputObject || !inputObject.spec || !containers) { existingImagePullSecretObjects = new Array();
return; }
} existingImagePullSecretObjects = existingImagePullSecretObjects.concat(newImagePullSecretsObjects);
if (inputObject.spec.template && !!inputObject.spec.template.spec) { }
if (inputObject.spec.template.spec.containers) { setImagePullSecrets(inputObject, existingImagePullSecretObjects);
updateContainers(inputObject.spec.template.spec.containers, containers); }
} exports.updateImagePullSecrets = updateImagePullSecrets;
if (inputObject.spec.template.spec.initContainers) { function updateSpecLabels(inputObject, newLabels, override) {
updateContainers(inputObject.spec.template.spec.initContainers, containers); if (!inputObject) {
} throw ('NullInputObject');
return; }
} if (!inputObject.kind) {
if (inputObject.spec.jobTemplate && inputObject.spec.jobTemplate.spec && inputObject.spec.jobTemplate.spec.template && inputObject.spec.jobTemplate.spec.template.spec) { throw ('ResourceKindNotDefined');
if (inputObject.spec.jobTemplate.spec.template.spec.containers) { }
updateContainers(inputObject.spec.jobTemplate.spec.template.spec.containers, containers); if (!newLabels) {
} return;
if (inputObject.spec.jobTemplate.spec.template.spec.initContainers) { }
updateContainers(inputObject.spec.jobTemplate.spec.template.spec.initContainers, containers); let existingLabels = getSpecLabels(inputObject);
} if (override) {
return; existingLabels = newLabels;
} }
if (inputObject.spec.containers) { else {
updateContainers(inputObject.spec.containers, containers); if (!existingLabels) {
} existingLabels = new Map();
if (inputObject.spec.initContainers) { }
updateContainers(inputObject.spec.initContainers, containers); Object.keys(newLabels).forEach(function (key) {
} existingLabels[key] = newLabels[key];
} });
exports.updateImageDetails = updateImageDetails; }
function updateContainers(containers, images) { setSpecLabels(inputObject, existingLabels);
if (!containers || containers.length === 0) { }
return containers; exports.updateSpecLabels = updateSpecLabels;
} function updateSelectorLabels(inputObject, newLabels, override) {
containers.forEach((container) => { if (!inputObject) {
const imageName = extractImageName(container.image.trim()); throw ('NullInputObject');
images.forEach(image => { }
if (extractImageName(image) === imageName) { if (!inputObject.kind) {
container.image = image; throw ('ResourceKindNotDefined');
} }
}); if (!newLabels) {
}); return;
} }
function extractImageName(imageName) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
let img = ''; return;
if (imageName.indexOf('/') > 0) { }
const registry = imageName.substring(0, imageName.indexOf('/')); let existingLabels = getSpecSelectorLabels(inputObject);
const imgName = imageName.substring(imageName.indexOf('/') + 1).split(':')[0]; if (override) {
img = `${registry}/${imgName}`; existingLabels = newLabels;
} }
else { else {
img = imageName.split(':')[0]; if (!existingLabels) {
} existingLabels = new Map();
return img; }
} Object.keys(newLabels).forEach(function (key) {
function updateSpecLabels(inputObject, newLabels, override) { existingLabels[key] = newLabels[key];
if (!inputObject) { });
throw ('NullInputObject'); }
} setSpecSelectorLabels(inputObject, existingLabels);
if (!inputObject.kind) { }
throw ('ResourceKindNotDefined'); exports.updateSelectorLabels = updateSelectorLabels;
} function getResources(filePaths, filterResourceTypes) {
if (!newLabels) { if (!filePaths) {
return; return [];
} }
let existingLabels = getSpecLabels(inputObject); const resources = [];
if (override) { filePaths.forEach((filePath) => {
existingLabels = newLabels; const fileContents = fs.readFileSync(filePath);
} yaml.safeLoadAll(fileContents, function (inputObject) {
else { const inputObjectKind = inputObject ? inputObject.kind : '';
if (!existingLabels) { if (filterResourceTypes.filter(type => string_comparison_1.isEqual(inputObjectKind, type, string_comparison_1.StringComparer.OrdinalIgnoreCase)).length > 0) {
existingLabels = new Map(); const resource = {
} type: inputObject.kind,
Object.keys(newLabels).forEach(function (key) { name: inputObject.metadata.name
existingLabels[key] = newLabels[key]; };
}); resources.push(resource);
} }
setSpecLabels(inputObject, existingLabels); });
} });
exports.updateSpecLabels = updateSpecLabels; return resources;
function updateSelectorLabels(inputObject, newLabels, override) { }
if (!inputObject) { exports.getResources = getResources;
throw ('NullInputObject'); function getSpecLabels(inputObject) {
} if (!inputObject) {
if (!inputObject.kind) { return null;
throw ('ResourceKindNotDefined'); }
} if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
if (!newLabels) { return inputObject.metadata.labels;
return; }
} if (!!inputObject.spec && !!inputObject.spec.template && !!inputObject.spec.template.metadata) {
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { return inputObject.spec.template.metadata.labels;
return; }
} return null;
let existingLabels = getSpecSelectorLabels(inputObject); }
if (override) { function getImagePullSecrets(inputObject) {
existingLabels = newLabels; if (!inputObject || !inputObject.spec) {
} return null;
else { }
if (!existingLabels) { if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
existingLabels = new Map(); try {
} return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets;
Object.keys(newLabels).forEach(function (key) { }
existingLabels[key] = newLabels[key]; catch (ex) {
}); core.debug(`Fetching imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
} return null;
setSpecSelectorLabels(inputObject, existingLabels); }
} }
exports.updateSelectorLabels = updateSelectorLabels; if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
function getResources(filePaths, filterResourceTypes) { return inputObject.spec.imagePullSecrets;
if (!filePaths) { }
return []; if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
} return inputObject.spec.template.spec.imagePullSecrets;
const resources = []; }
filePaths.forEach((filePath) => { return null;
const fileContents = fs.readFileSync(filePath); }
yaml.safeLoadAll(fileContents, function (inputObject) { function setImagePullSecrets(inputObject, newImagePullSecrets) {
const inputObjectKind = inputObject ? inputObject.kind : ''; if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
if (filterResourceTypes.filter(type => string_comparison_1.isEqual(inputObjectKind, type, string_comparison_1.StringComparer.OrdinalIgnoreCase)).length > 0) { return;
const resource = { }
type: inputObject.kind, if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
name: inputObject.metadata.name inputObject.spec.imagePullSecrets = newImagePullSecrets;
}; return;
resources.push(resource); }
} if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
}); try {
}); inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
return resources; }
} catch (ex) {
exports.getResources = getResources; core.debug(`Overriding imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
function getSpecLabels(inputObject) { //Do nothing
if (!inputObject) { }
return null; return;
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
return inputObject.metadata.labels; inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
} return;
if (!!inputObject.spec && !!inputObject.spec.template && !!inputObject.spec.template.metadata) { }
return inputObject.spec.template.metadata.labels; return;
} }
return null; function setSpecLabels(inputObject, newLabels) {
} let specLabels = getSpecLabels(inputObject);
function getImagePullSecrets(inputObject) { if (!!newLabels) {
if (!inputObject || !inputObject.spec) { specLabels = newLabels;
return null; }
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { function getSpecSelectorLabels(inputObject) {
try { if (!!inputObject && !!inputObject.spec && !!inputObject.spec.selector) {
return inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets; if (isServiceEntity(inputObject.kind)) {
} return inputObject.spec.selector;
catch (ex) { }
core.debug(`Fetching imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`); else {
return null; return inputObject.spec.selector.matchLabels;
} }
} }
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) { return null;
return inputObject.spec.imagePullSecrets; }
} function setSpecSelectorLabels(inputObject, newLabels) {
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) { let selectorLabels = getSpecSelectorLabels(inputObject);
return inputObject.spec.template.spec.imagePullSecrets; if (!!selectorLabels) {
} selectorLabels = newLabels;
return null; }
} }
function setImagePullSecrets(inputObject, newImagePullSecrets) {
if (!inputObject || !inputObject.spec || !newImagePullSecrets) {
return;
}
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
inputObject.spec.imagePullSecrets = newImagePullSecrets;
return;
}
if (string_comparison_1.isEqual(inputObject.kind, constants_1.KubernetesWorkload.cronjob, string_comparison_1.StringComparer.OrdinalIgnoreCase)) {
try {
inputObject.spec.jobTemplate.spec.template.spec.imagePullSecrets = newImagePullSecrets;
}
catch (ex) {
core.debug(`Overriding imagePullSecrets failed due to this error: ${JSON.stringify(ex)}`);
//Do nothing
}
return;
}
if (!!inputObject.spec.template && !!inputObject.spec.template.spec) {
inputObject.spec.template.spec.imagePullSecrets = newImagePullSecrets;
return;
}
return;
}
function setSpecLabels(inputObject, newLabels) {
let specLabels = getSpecLabels(inputObject);
if (!!newLabels) {
specLabels = newLabels;
}
}
function getSpecSelectorLabels(inputObject) {
if (!!inputObject && !!inputObject.spec && !!inputObject.spec.selector) {
if (isServiceEntity(inputObject.kind)) {
return inputObject.spec.selector;
}
else {
return inputObject.spec.selector.matchLabels;
}
}
return null;
}
function setSpecSelectorLabels(inputObject, newLabels) {
let selectorLabels = getSpecSelectorLabels(inputObject);
if (!!selectorLabels) {
selectorLabels = newLabels;
}
}
@@ -0,0 +1,305 @@
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchResource = exports.isServiceSelectorSubsetOfMatchLabel = exports.getServiceSelector = exports.getDeploymentMatchLabels = exports.getBlueGreenResourceName = exports.addBlueGreenLabelsAndAnnotations = exports.getNewBlueGreenObject = exports.createWorkloadsWithLabel = exports.isServiceRouted = exports.getManifestObjects = exports.getSuffix = exports.deleteObjects = exports.deleteWorkloadsAndServicesWithLabel = exports.deleteWorkloadsWithLabel = exports.routeBlueGreen = exports.isSMIRoute = exports.isIngressRoute = exports.isBlueGreenDeploymentStrategy = exports.STABLE_SUFFIX = exports.GREEN_SUFFIX = exports.BLUE_GREEN_VERSION_LABEL = exports.NONE_LABEL_VALUE = exports.GREEN_LABEL_VALUE = exports.BLUE_GREEN_DEPLOYMENT_STRATEGY = void 0;
const core = require("@actions/core");
const fs = require("fs");
const yaml = require("js-yaml");
const utility_1 = require("../utility");
const constants_1 = require("../../constants");
const fileHelper = require("../files-helper");
const helper = require("../resource-object-utility");
const TaskInputParameters = require("../../input-parameters");
const service_blue_green_helper_1 = require("./service-blue-green-helper");
const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
exports.BLUE_GREEN_DEPLOYMENT_STRATEGY = 'BLUE-GREEN';
exports.GREEN_LABEL_VALUE = 'green';
exports.NONE_LABEL_VALUE = 'None';
exports.BLUE_GREEN_VERSION_LABEL = 'k8s.deploy.color';
exports.GREEN_SUFFIX = '-green';
exports.STABLE_SUFFIX = '-stable';
const INGRESS_ROUTE = 'INGRESS';
const SMI_ROUTE = 'SMI';
function isBlueGreenDeploymentStrategy() {
const deploymentStrategy = TaskInputParameters.deploymentStrategy;
return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.BLUE_GREEN_DEPLOYMENT_STRATEGY;
}
exports.isBlueGreenDeploymentStrategy = isBlueGreenDeploymentStrategy;
function isIngressRoute() {
const routeMethod = TaskInputParameters.routeMethod;
return routeMethod && routeMethod.toUpperCase() === INGRESS_ROUTE;
}
exports.isIngressRoute = isIngressRoute;
function isSMIRoute() {
const routeMethod = TaskInputParameters.routeMethod;
return routeMethod && routeMethod.toUpperCase() === SMI_ROUTE;
}
exports.isSMIRoute = isSMIRoute;
function routeBlueGreen(kubectl, inputManifestFiles) {
return __awaiter(this, void 0, void 0, function* () {
// get buffer time
let bufferTime = parseInt(TaskInputParameters.versionSwitchBuffer);
//logging start of buffer time
let dateNow = new Date();
console.log(`Starting buffer time of ${bufferTime} minute(s) at ${dateNow.toISOString()}`);
// waiting
yield utility_1.sleep(bufferTime * 1000 * 60);
// logging end of buffer time
dateNow = new Date();
console.log(`Stopping buffer time of ${bufferTime} minute(s) at ${dateNow.toISOString()}`);
const manifestObjects = getManifestObjects(inputManifestFiles);
// routing to new deployments
if (isIngressRoute()) {
ingress_blue_green_helper_1.routeBlueGreenIngress(kubectl, exports.GREEN_LABEL_VALUE, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
}
else if (isSMIRoute()) {
smi_blue_green_helper_1.routeBlueGreenSMI(kubectl, exports.GREEN_LABEL_VALUE, manifestObjects.serviceEntityList);
}
else {
service_blue_green_helper_1.routeBlueGreenService(kubectl, exports.GREEN_LABEL_VALUE, manifestObjects.serviceEntityList);
}
});
}
exports.routeBlueGreen = routeBlueGreen;
function deleteWorkloadsWithLabel(kubectl, deleteLabel, deploymentEntityList) {
let resourcesToDelete = [];
deploymentEntityList.forEach((inputObject) => {
const name = inputObject.metadata.name;
const kind = inputObject.kind;
if (deleteLabel === exports.NONE_LABEL_VALUE) {
// if dellabel is none, deletes stable deployments
const resourceToDelete = { name: name, kind: kind };
resourcesToDelete.push(resourceToDelete);
}
else {
// if dellabel is not none, then deletes new green deployments
const resourceToDelete = { name: getBlueGreenResourceName(name, exports.GREEN_SUFFIX), kind: kind };
resourcesToDelete.push(resourceToDelete);
}
});
// deletes the deployments
deleteObjects(kubectl, resourcesToDelete);
}
exports.deleteWorkloadsWithLabel = deleteWorkloadsWithLabel;
function deleteWorkloadsAndServicesWithLabel(kubectl, deleteLabel, deploymentEntityList, serviceEntityList) {
// need to delete services and deployments
const deletionEntitiesList = deploymentEntityList.concat(serviceEntityList);
let resourcesToDelete = [];
deletionEntitiesList.forEach((inputObject) => {
const name = inputObject.metadata.name;
const kind = inputObject.kind;
if (deleteLabel === exports.NONE_LABEL_VALUE) {
// if not dellabel, delete stable objects
const resourceToDelete = { name: name, kind: kind };
resourcesToDelete.push(resourceToDelete);
}
else {
// else delete green labels
const resourceToDelete = { name: getBlueGreenResourceName(name, exports.GREEN_SUFFIX), kind: kind };
resourcesToDelete.push(resourceToDelete);
}
});
deleteObjects(kubectl, resourcesToDelete);
}
exports.deleteWorkloadsAndServicesWithLabel = deleteWorkloadsAndServicesWithLabel;
function deleteObjects(kubectl, deleteList) {
// delete services and deployments
deleteList.forEach((delObject) => {
try {
const result = kubectl.delete([delObject.kind, delObject.name]);
utility_1.checkForErrors([result]);
}
catch (ex) {
// Ignore failures of delete if doesn't exist
}
});
}
exports.deleteObjects = deleteObjects;
function getSuffix(label) {
if (label === exports.GREEN_LABEL_VALUE) {
return exports.GREEN_SUFFIX;
}
else {
return '';
}
}
exports.getSuffix = getSuffix;
// other common functions
function getManifestObjects(filePaths) {
const deploymentEntityList = [];
const routedServiceEntityList = [];
const unroutedServiceEntityList = [];
const ingressEntityList = [];
const otherEntitiesList = [];
let serviceNameMap = new Map();
filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) {
if (!!inputObject) {
const kind = inputObject.kind;
const name = inputObject.metadata.name;
if (helper.isDeploymentEntity(kind)) {
deploymentEntityList.push(inputObject);
}
else if (helper.isServiceEntity(kind)) {
if (isServiceRouted(inputObject, deploymentEntityList)) {
routedServiceEntityList.push(inputObject);
serviceNameMap.set(name, getBlueGreenResourceName(name, exports.GREEN_SUFFIX));
}
else {
unroutedServiceEntityList.push(inputObject);
}
}
else if (helper.isIngressEntity(kind)) {
ingressEntityList.push(inputObject);
}
else {
otherEntitiesList.push(inputObject);
}
}
});
});
return { serviceEntityList: routedServiceEntityList, serviceNameMap: serviceNameMap, unroutedServiceEntityList: unroutedServiceEntityList, deploymentEntityList: deploymentEntityList, ingressEntityList: ingressEntityList, otherObjects: otherEntitiesList };
}
exports.getManifestObjects = getManifestObjects;
function isServiceRouted(serviceObject, deploymentEntityList) {
let shouldBeRouted = false;
const serviceSelector = getServiceSelector(serviceObject);
if (!!serviceSelector) {
if (deploymentEntityList.some((depObject) => {
// finding if there is a deployment in the given manifests the service targets
const matchLabels = getDeploymentMatchLabels(depObject);
return (!!matchLabels && isServiceSelectorSubsetOfMatchLabel(serviceSelector, matchLabels));
})) {
shouldBeRouted = true;
}
}
return shouldBeRouted;
}
exports.isServiceRouted = isServiceRouted;
function createWorkloadsWithLabel(kubectl, deploymentObjectList, nextLabel) {
const newObjectsList = [];
deploymentObjectList.forEach((inputObject) => {
// creating deployment with label
const newBlueGreenObject = getNewBlueGreenObject(inputObject, nextLabel);
core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject));
newObjectsList.push(newBlueGreenObject);
});
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
const result = kubectl.apply(manifestFiles);
return { 'result': result, 'newFilePaths': manifestFiles };
}
exports.createWorkloadsWithLabel = createWorkloadsWithLabel;
function getNewBlueGreenObject(inputObject, labelValue) {
const newObject = JSON.parse(JSON.stringify(inputObject));
// Updating name only if label is green label is given
if (labelValue === exports.GREEN_LABEL_VALUE) {
newObject.metadata.name = getBlueGreenResourceName(inputObject.metadata.name, exports.GREEN_SUFFIX);
}
// Adding labels and annotations
addBlueGreenLabelsAndAnnotations(newObject, labelValue);
return newObject;
}
exports.getNewBlueGreenObject = getNewBlueGreenObject;
function addBlueGreenLabelsAndAnnotations(inputObject, labelValue) {
//creating the k8s.deploy.color label
const newLabels = new Map();
newLabels[exports.BLUE_GREEN_VERSION_LABEL] = labelValue;
// updating object labels and selector labels
helper.updateObjectLabels(inputObject, newLabels, false);
helper.updateSelectorLabels(inputObject, newLabels, false);
// updating spec labels if it is a service
if (!helper.isServiceEntity(inputObject.kind)) {
helper.updateSpecLabels(inputObject, newLabels, false);
}
}
exports.addBlueGreenLabelsAndAnnotations = addBlueGreenLabelsAndAnnotations;
function getBlueGreenResourceName(name, suffix) {
return `${name}${suffix}`;
}
exports.getBlueGreenResourceName = getBlueGreenResourceName;
function getDeploymentMatchLabels(deploymentObject) {
if (!!deploymentObject && deploymentObject.kind.toUpperCase() == constants_1.KubernetesWorkload.pod.toUpperCase() && !!deploymentObject.metadata && !!deploymentObject.metadata.labels) {
return deploymentObject.metadata.labels;
}
else if (!!deploymentObject && deploymentObject.spec && deploymentObject.spec.selector && deploymentObject.spec.selector.matchLabels) {
return deploymentObject.spec.selector.matchLabels;
}
return null;
}
exports.getDeploymentMatchLabels = getDeploymentMatchLabels;
function getServiceSelector(serviceObject) {
if (!!serviceObject && serviceObject.spec && serviceObject.spec.selector) {
return serviceObject.spec.selector;
}
else
return null;
}
exports.getServiceSelector = getServiceSelector;
function isServiceSelectorSubsetOfMatchLabel(serviceSelector, matchLabels) {
let serviceSelectorMap = new Map();
let matchLabelsMap = new Map();
JSON.parse(JSON.stringify(serviceSelector), (key, value) => {
serviceSelectorMap.set(key, value);
});
JSON.parse(JSON.stringify(matchLabels), (key, value) => {
matchLabelsMap.set(key, value);
});
let isMatch = true;
serviceSelectorMap.forEach((value, key) => {
if (!!key && (!matchLabelsMap.has(key) || matchLabelsMap.get(key)) != value) {
isMatch = false;
}
});
return isMatch;
}
exports.isServiceSelectorSubsetOfMatchLabel = isServiceSelectorSubsetOfMatchLabel;
function fetchResource(kubectl, kind, name) {
const result = kubectl.getResource(kind, name);
if (result == null || !!result.stderr) {
return null;
}
if (!!result.stdout) {
const resource = JSON.parse(result.stdout);
try {
UnsetsClusterSpecficDetails(resource);
return resource;
}
catch (ex) {
core.debug('Exception occurred while Parsing ' + resource + ' in Json object');
core.debug(`Exception:${ex}`);
}
}
return null;
}
exports.fetchResource = fetchResource;
function UnsetsClusterSpecficDetails(resource) {
if (resource == null) {
return;
}
// Unsets the cluster specific details in the object
if (!!resource) {
const metadata = resource.metadata;
const status = resource.status;
if (!!metadata) {
const newMetadata = {
'annotations': metadata.annotations,
'labels': metadata.labels,
'name': metadata.name
};
resource.metadata = newMetadata;
}
if (!!status) {
resource.status = {};
}
}
}
@@ -1,187 +1,187 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.getStableResourceName = exports.getBaselineResourceName = exports.getCanaryResourceName = exports.isSMICanaryStrategy = exports.isCanaryDeploymentStrategy = exports.fetchResource = exports.fetchCanaryResource = exports.getNewCanaryResource = exports.getNewBaselineResource = exports.getStableResource = exports.isResourceMarkedAsStable = exports.markResourceAsStable = exports.deleteCanaryDeployment = exports.STABLE_LABEL_VALUE = exports.STABLE_SUFFIX = exports.CANARY_LABEL_VALUE = exports.BASELINE_LABEL_VALUE = exports.CANARY_VERSION_LABEL = exports.TRAFFIC_SPLIT_STRATEGY = exports.CANARY_DEPLOYMENT_STRATEGY = void 0; exports.getStableResourceName = exports.getBaselineResourceName = exports.getCanaryResourceName = exports.isSMICanaryStrategy = exports.isCanaryDeploymentStrategy = exports.fetchResource = exports.fetchCanaryResource = exports.getNewCanaryResource = exports.getNewBaselineResource = exports.getStableResource = exports.isResourceMarkedAsStable = exports.markResourceAsStable = exports.deleteCanaryDeployment = exports.STABLE_LABEL_VALUE = exports.STABLE_SUFFIX = exports.CANARY_LABEL_VALUE = exports.BASELINE_LABEL_VALUE = exports.CANARY_VERSION_LABEL = exports.TRAFFIC_SPLIT_STRATEGY = exports.CANARY_DEPLOYMENT_STRATEGY = void 0;
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const core = require("@actions/core"); const core = require("@actions/core");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const helper = require("../resource-object-utility"); const helper = require("../resource-object-utility");
const constants_1 = require("../../constants"); const constants_1 = require("../../constants");
const string_comparison_1 = require("../string-comparison"); const string_comparison_1 = require("../string-comparison");
const utility_1 = require("../utility"); const utility_1 = require("../utility");
const utils = require("../manifest-utilities"); const utils = require("../manifest-utilities");
exports.CANARY_DEPLOYMENT_STRATEGY = 'CANARY'; exports.CANARY_DEPLOYMENT_STRATEGY = 'CANARY';
exports.TRAFFIC_SPLIT_STRATEGY = 'SMI'; exports.TRAFFIC_SPLIT_STRATEGY = 'SMI';
exports.CANARY_VERSION_LABEL = 'workflow/version'; exports.CANARY_VERSION_LABEL = 'workflow/version';
const BASELINE_SUFFIX = '-baseline'; const BASELINE_SUFFIX = '-baseline';
exports.BASELINE_LABEL_VALUE = 'baseline'; exports.BASELINE_LABEL_VALUE = 'baseline';
const CANARY_SUFFIX = '-canary'; const CANARY_SUFFIX = '-canary';
exports.CANARY_LABEL_VALUE = 'canary'; exports.CANARY_LABEL_VALUE = 'canary';
exports.STABLE_SUFFIX = '-stable'; exports.STABLE_SUFFIX = '-stable';
exports.STABLE_LABEL_VALUE = 'stable'; exports.STABLE_LABEL_VALUE = 'stable';
function deleteCanaryDeployment(kubectl, manifestFilePaths, includeServices) { function deleteCanaryDeployment(kubectl, manifestFilePaths, includeServices) {
// get manifest files // get manifest files
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths); const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
if (inputManifestFiles == null || inputManifestFiles.length == 0) { if (inputManifestFiles == null || inputManifestFiles.length == 0) {
throw new Error('ManifestFileNotFound'); throw new Error('ManifestFileNotFound');
} }
// create delete cmd prefix // create delete cmd prefix
cleanUpCanary(kubectl, inputManifestFiles, includeServices); cleanUpCanary(kubectl, inputManifestFiles, includeServices);
} }
exports.deleteCanaryDeployment = deleteCanaryDeployment; exports.deleteCanaryDeployment = deleteCanaryDeployment;
function markResourceAsStable(inputObject) { function markResourceAsStable(inputObject) {
if (isResourceMarkedAsStable(inputObject)) { if (isResourceMarkedAsStable(inputObject)) {
return inputObject; return inputObject;
} }
const newObject = JSON.parse(JSON.stringify(inputObject)); const newObject = JSON.parse(JSON.stringify(inputObject));
// Adding labels and annotations. // Adding labels and annotations.
addCanaryLabelsAndAnnotations(newObject, exports.STABLE_LABEL_VALUE); addCanaryLabelsAndAnnotations(newObject, exports.STABLE_LABEL_VALUE);
core.debug("Added stable label: " + JSON.stringify(newObject)); core.debug("Added stable label: " + JSON.stringify(newObject));
return newObject; return newObject;
} }
exports.markResourceAsStable = markResourceAsStable; exports.markResourceAsStable = markResourceAsStable;
function isResourceMarkedAsStable(inputObject) { function isResourceMarkedAsStable(inputObject) {
return inputObject && return inputObject &&
inputObject.metadata && inputObject.metadata &&
inputObject.metadata.labels && inputObject.metadata.labels &&
inputObject.metadata.labels[exports.CANARY_VERSION_LABEL] == exports.STABLE_LABEL_VALUE; inputObject.metadata.labels[exports.CANARY_VERSION_LABEL] == exports.STABLE_LABEL_VALUE;
} }
exports.isResourceMarkedAsStable = isResourceMarkedAsStable; exports.isResourceMarkedAsStable = isResourceMarkedAsStable;
function getStableResource(inputObject) { function getStableResource(inputObject) {
var replicaCount = isSpecContainsReplicas(inputObject.kind) ? inputObject.metadata.replicas : 0; var replicaCount = isSpecContainsReplicas(inputObject.kind) ? inputObject.metadata.replicas : 0;
return getNewCanaryObject(inputObject, replicaCount, exports.STABLE_LABEL_VALUE); return getNewCanaryObject(inputObject, replicaCount, exports.STABLE_LABEL_VALUE);
} }
exports.getStableResource = getStableResource; exports.getStableResource = getStableResource;
function getNewBaselineResource(stableObject, replicas) { function getNewBaselineResource(stableObject, replicas) {
return getNewCanaryObject(stableObject, replicas, exports.BASELINE_LABEL_VALUE); return getNewCanaryObject(stableObject, replicas, exports.BASELINE_LABEL_VALUE);
} }
exports.getNewBaselineResource = getNewBaselineResource; exports.getNewBaselineResource = getNewBaselineResource;
function getNewCanaryResource(inputObject, replicas) { function getNewCanaryResource(inputObject, replicas) {
return getNewCanaryObject(inputObject, replicas, exports.CANARY_LABEL_VALUE); return getNewCanaryObject(inputObject, replicas, exports.CANARY_LABEL_VALUE);
} }
exports.getNewCanaryResource = getNewCanaryResource; exports.getNewCanaryResource = getNewCanaryResource;
function fetchCanaryResource(kubectl, kind, name) { function fetchCanaryResource(kubectl, kind, name) {
return fetchResource(kubectl, kind, getCanaryResourceName(name)); return fetchResource(kubectl, kind, getCanaryResourceName(name));
} }
exports.fetchCanaryResource = fetchCanaryResource; exports.fetchCanaryResource = fetchCanaryResource;
function fetchResource(kubectl, kind, name) { function fetchResource(kubectl, kind, name) {
const result = kubectl.getResource(kind, name); const result = kubectl.getResource(kind, name);
if (result == null || !!result.stderr) { if (result == null || !!result.stderr) {
return null; return null;
} }
if (!!result.stdout) { if (!!result.stdout) {
const resource = JSON.parse(result.stdout); const resource = JSON.parse(result.stdout);
try { try {
UnsetsClusterSpecficDetails(resource); UnsetsClusterSpecficDetails(resource);
return resource; return resource;
} }
catch (ex) { catch (ex) {
core.debug('Exception occurred while Parsing ' + resource + ' in Json object'); core.debug('Exception occurred while Parsing ' + resource + ' in Json object');
core.debug(`Exception:${ex}`); core.debug(`Exception:${ex}`);
} }
} }
return null; return null;
} }
exports.fetchResource = fetchResource; exports.fetchResource = fetchResource;
function isCanaryDeploymentStrategy() { function isCanaryDeploymentStrategy() {
const deploymentStrategy = TaskInputParameters.deploymentStrategy; const deploymentStrategy = TaskInputParameters.deploymentStrategy;
return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.CANARY_DEPLOYMENT_STRATEGY; return deploymentStrategy && deploymentStrategy.toUpperCase() === exports.CANARY_DEPLOYMENT_STRATEGY;
} }
exports.isCanaryDeploymentStrategy = isCanaryDeploymentStrategy; exports.isCanaryDeploymentStrategy = isCanaryDeploymentStrategy;
function isSMICanaryStrategy() { function isSMICanaryStrategy() {
const deploymentStrategy = TaskInputParameters.trafficSplitMethod; const deploymentStrategy = TaskInputParameters.trafficSplitMethod;
return isCanaryDeploymentStrategy() && deploymentStrategy && deploymentStrategy.toUpperCase() === exports.TRAFFIC_SPLIT_STRATEGY; return isCanaryDeploymentStrategy() && deploymentStrategy && deploymentStrategy.toUpperCase() === exports.TRAFFIC_SPLIT_STRATEGY;
} }
exports.isSMICanaryStrategy = isSMICanaryStrategy; exports.isSMICanaryStrategy = isSMICanaryStrategy;
function getCanaryResourceName(name) { function getCanaryResourceName(name) {
return name + CANARY_SUFFIX; return name + CANARY_SUFFIX;
} }
exports.getCanaryResourceName = getCanaryResourceName; exports.getCanaryResourceName = getCanaryResourceName;
function getBaselineResourceName(name) { function getBaselineResourceName(name) {
return name + BASELINE_SUFFIX; return name + BASELINE_SUFFIX;
} }
exports.getBaselineResourceName = getBaselineResourceName; exports.getBaselineResourceName = getBaselineResourceName;
function getStableResourceName(name) { function getStableResourceName(name) {
return name + exports.STABLE_SUFFIX; return name + exports.STABLE_SUFFIX;
} }
exports.getStableResourceName = getStableResourceName; exports.getStableResourceName = getStableResourceName;
function UnsetsClusterSpecficDetails(resource) { function UnsetsClusterSpecficDetails(resource) {
if (resource == null) { if (resource == null) {
return; return;
} }
// Unsets the cluster specific details in the object // Unsets the cluster specific details in the object
if (!!resource) { if (!!resource) {
const metadata = resource.metadata; const metadata = resource.metadata;
const status = resource.status; const status = resource.status;
if (!!metadata) { if (!!metadata) {
const newMetadata = { const newMetadata = {
'annotations': metadata.annotations, 'annotations': metadata.annotations,
'labels': metadata.labels, 'labels': metadata.labels,
'name': metadata.name 'name': metadata.name
}; };
resource.metadata = newMetadata; resource.metadata = newMetadata;
} }
if (!!status) { if (!!status) {
resource.status = {}; resource.status = {};
} }
} }
} }
function getNewCanaryObject(inputObject, replicas, type) { function getNewCanaryObject(inputObject, replicas, type) {
const newObject = JSON.parse(JSON.stringify(inputObject)); const newObject = JSON.parse(JSON.stringify(inputObject));
// Updating name // Updating name
if (type === exports.CANARY_LABEL_VALUE) { if (type === exports.CANARY_LABEL_VALUE) {
newObject.metadata.name = getCanaryResourceName(inputObject.metadata.name); newObject.metadata.name = getCanaryResourceName(inputObject.metadata.name);
} }
else if (type === exports.STABLE_LABEL_VALUE) { else if (type === exports.STABLE_LABEL_VALUE) {
newObject.metadata.name = getStableResourceName(inputObject.metadata.name); newObject.metadata.name = getStableResourceName(inputObject.metadata.name);
} }
else { else {
newObject.metadata.name = getBaselineResourceName(inputObject.metadata.name); newObject.metadata.name = getBaselineResourceName(inputObject.metadata.name);
} }
// Adding labels and annotations. // Adding labels and annotations.
addCanaryLabelsAndAnnotations(newObject, type); addCanaryLabelsAndAnnotations(newObject, type);
// Updating no. of replicas // Updating no. of replicas
if (isSpecContainsReplicas(newObject.kind)) { if (isSpecContainsReplicas(newObject.kind)) {
newObject.spec.replicas = replicas; newObject.spec.replicas = replicas;
} }
return newObject; return newObject;
} }
function isSpecContainsReplicas(kind) { function isSpecContainsReplicas(kind) {
return !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) && return !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.pod, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
!string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase) && !string_comparison_1.isEqual(kind, constants_1.KubernetesWorkload.daemonSet, string_comparison_1.StringComparer.OrdinalIgnoreCase) &&
!helper.isServiceEntity(kind); !helper.isServiceEntity(kind);
} }
function addCanaryLabelsAndAnnotations(inputObject, type) { function addCanaryLabelsAndAnnotations(inputObject, type) {
const newLabels = new Map(); const newLabels = new Map();
newLabels[exports.CANARY_VERSION_LABEL] = type; newLabels[exports.CANARY_VERSION_LABEL] = type;
helper.updateObjectLabels(inputObject, newLabels, false); helper.updateObjectLabels(inputObject, newLabels, false);
helper.updateObjectAnnotations(inputObject, newLabels, false); helper.updateObjectAnnotations(inputObject, newLabels, false);
helper.updateSelectorLabels(inputObject, newLabels, false); helper.updateSelectorLabels(inputObject, newLabels, false);
if (!helper.isServiceEntity(inputObject.kind)) { if (!helper.isServiceEntity(inputObject.kind)) {
helper.updateSpecLabels(inputObject, newLabels, false); helper.updateSpecLabels(inputObject, newLabels, false);
} }
} }
function cleanUpCanary(kubectl, files, includeServices) { function cleanUpCanary(kubectl, files, includeServices) {
var deleteObject = function (kind, name) { var deleteObject = function (kind, name) {
try { try {
const result = kubectl.delete([kind, name]); const result = kubectl.delete([kind, name]);
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
} }
catch (ex) { catch (ex) {
// Ignore failures of delete if doesn't exist // Ignore failures of delete if doesn't exist
} }
}; };
files.forEach((filePath) => { files.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isDeploymentEntity(kind) || (includeServices && helper.isServiceEntity(kind))) { if (helper.isDeploymentEntity(kind) || (includeServices && helper.isServiceEntity(kind))) {
const canaryObjectName = getCanaryResourceName(name); const canaryObjectName = getCanaryResourceName(name);
const baselineObjectName = getBaselineResourceName(name); const baselineObjectName = getBaselineResourceName(name);
deleteObject(kind, canaryObjectName); deleteObject(kind, canaryObjectName);
deleteObject(kind, baselineObjectName); deleteObject(kind, baselineObjectName);
} }
}); });
}); });
} }
@@ -1,159 +1,166 @@
'use strict'; 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.deploy = void 0; exports.getManifestFiles = exports.deploy = void 0;
const fs = require("fs"); const fs = require("fs");
const core = require("@actions/core"); const core = require("@actions/core");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const canaryDeploymentHelper = require("./canary-deployment-helper"); const canaryDeploymentHelper = require("./canary-deployment-helper");
const KubernetesObjectUtility = require("../resource-object-utility"); const KubernetesObjectUtility = require("../resource-object-utility");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const models = require("../../constants"); const models = require("../../constants");
const fileHelper = require("../files-helper"); const fileHelper = require("../files-helper");
const utils = require("../manifest-utilities"); const utils = require("../manifest-utilities");
const KubernetesManifestUtility = require("../manifest-stability-utility"); const KubernetesManifestUtility = require("../manifest-stability-utility");
const KubernetesConstants = require("../../constants"); const KubernetesConstants = require("../../constants");
const string_comparison_1 = require("./../string-comparison"); const manifest_utilities_1 = require("../manifest-utilities");
const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper"); const pod_canary_deployment_helper_1 = require("./pod-canary-deployment-helper");
const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper"); const smi_canary_deployment_helper_1 = require("./smi-canary-deployment-helper");
const utility_1 = require("../utility"); const utility_1 = require("../utility");
function deploy(kubectl, manifestFilePaths, deploymentStrategy) { const blue_green_helper_1 = require("./blue-green-helper");
return __awaiter(this, void 0, void 0, function* () { const service_blue_green_helper_1 = require("./service-blue-green-helper");
// get manifest files const ingress_blue_green_helper_1 = require("./ingress-blue-green-helper");
let inputManifestFiles = getManifestFiles(manifestFilePaths); const smi_blue_green_helper_1 = require("./smi-blue-green-helper");
// artifact substitution function deploy(kubectl, manifestFilePaths, deploymentStrategy) {
inputManifestFiles = updateResourceObjects(inputManifestFiles, TaskInputParameters.imagePullSecrets, TaskInputParameters.containers); return __awaiter(this, void 0, void 0, function* () {
// deployment // get manifest files
const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy)); let inputManifestFiles = manifest_utilities_1.getUpdatedManifestFiles(manifestFilePaths);
// check manifest stability // deployment
const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service])); const deployedManifestFiles = deployManifests(inputManifestFiles, kubectl, isCanaryDeploymentStrategy(deploymentStrategy), blue_green_helper_1.isBlueGreenDeploymentStrategy());
yield checkManifestStability(kubectl, resourceTypes); // check manifest stability
// print ingress resources const resourceTypes = KubernetesObjectUtility.getResources(deployedManifestFiles, models.deploymentTypes.concat([KubernetesConstants.DiscoveryAndLoadBalancerResource.service]));
const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]); yield checkManifestStability(kubectl, resourceTypes);
ingressResources.forEach(ingressResource => { // route blue-green deployments
kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name); if (blue_green_helper_1.isBlueGreenDeploymentStrategy()) {
}); yield blue_green_helper_1.routeBlueGreen(kubectl, inputManifestFiles);
// annotate resources }
let allPods; // print ingress resources
try { const ingressResources = KubernetesObjectUtility.getResources(deployedManifestFiles, [KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress]);
allPods = JSON.parse((kubectl.getAllPods()).stdout); ingressResources.forEach(ingressResource => {
} kubectl.getResource(KubernetesConstants.DiscoveryAndLoadBalancerResource.ingress, ingressResource.name);
catch (e) { });
core.debug("Unable to parse pods; Error: " + e); // annotate resources
} let allPods;
annotateResources(deployedManifestFiles, kubectl, resourceTypes, allPods); try {
}); allPods = JSON.parse((kubectl.getAllPods()).stdout);
} }
exports.deploy = deploy; catch (e) {
function getManifestFiles(manifestFilePaths) { core.debug("Unable to parse pods; Error: " + e);
const files = utils.getManifestFiles(manifestFilePaths); }
if (files == null || files.length === 0) { annotateAndLabelResources(deployedManifestFiles, kubectl, resourceTypes, allPods);
throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`); });
} }
return files; exports.deploy = deploy;
} function getManifestFiles(manifestFilePaths) {
function deployManifests(files, kubectl, isCanaryDeploymentStrategy) { const files = utils.getManifestFiles(manifestFilePaths);
let result; if (files == null || files.length === 0) {
if (isCanaryDeploymentStrategy) { throw new Error(`ManifestFileNotFound : ${manifestFilePaths}`);
let canaryDeploymentOutput; }
if (canaryDeploymentHelper.isSMICanaryStrategy()) { return files;
canaryDeploymentOutput = smi_canary_deployment_helper_1.deploySMICanary(kubectl, files); }
} exports.getManifestFiles = getManifestFiles;
else { function deployManifests(files, kubectl, isCanaryDeploymentStrategy, isBlueGreenDeploymentStrategy) {
canaryDeploymentOutput = pod_canary_deployment_helper_1.deployPodCanary(kubectl, files); let result;
} if (isCanaryDeploymentStrategy) {
result = canaryDeploymentOutput.result; let canaryDeploymentOutput;
files = canaryDeploymentOutput.newFilePaths; if (canaryDeploymentHelper.isSMICanaryStrategy()) {
} canaryDeploymentOutput = smi_canary_deployment_helper_1.deploySMICanary(kubectl, files);
else { }
if (canaryDeploymentHelper.isSMICanaryStrategy()) { else {
const updatedManifests = appendStableVersionLabelToResource(files, kubectl); canaryDeploymentOutput = pod_canary_deployment_helper_1.deployPodCanary(kubectl, files);
result = kubectl.apply(updatedManifests, TaskInputParameters.forceDeployment); }
} result = canaryDeploymentOutput.result;
else { files = canaryDeploymentOutput.newFilePaths;
result = kubectl.apply(files, TaskInputParameters.forceDeployment); }
} else if (isBlueGreenDeploymentStrategy) {
} let blueGreenDeploymentOutput;
utility_1.checkForErrors([result]); if (blue_green_helper_1.isIngressRoute()) {
return files; blueGreenDeploymentOutput = ingress_blue_green_helper_1.deployBlueGreenIngress(kubectl, files);
} }
function appendStableVersionLabelToResource(files, kubectl) { else if (blue_green_helper_1.isSMIRoute()) {
const manifestFiles = []; blueGreenDeploymentOutput = smi_blue_green_helper_1.deployBlueGreenSMI(kubectl, files);
const newObjectsList = []; }
files.forEach((filePath) => { else {
const fileContents = fs.readFileSync(filePath); blueGreenDeploymentOutput = service_blue_green_helper_1.deployBlueGreenService(kubectl, files);
yaml.safeLoadAll(fileContents, function (inputObject) { }
const kind = inputObject.kind; result = blueGreenDeploymentOutput.result;
if (KubernetesObjectUtility.isDeploymentEntity(kind)) { files = blueGreenDeploymentOutput.newFilePaths;
const updatedObject = canaryDeploymentHelper.markResourceAsStable(inputObject); }
newObjectsList.push(updatedObject); else {
} if (canaryDeploymentHelper.isSMICanaryStrategy()) {
else { const updatedManifests = appendStableVersionLabelToResource(files, kubectl);
manifestFiles.push(filePath); result = kubectl.apply(updatedManifests, TaskInputParameters.forceDeployment);
} }
}); else {
}); result = kubectl.apply(files, TaskInputParameters.forceDeployment);
const updatedManifestFiles = fileHelper.writeObjectsToFile(newObjectsList); }
manifestFiles.push(...updatedManifestFiles); }
return manifestFiles; utility_1.checkForErrors([result]);
} return files;
function checkManifestStability(kubectl, resources) { }
return __awaiter(this, void 0, void 0, function* () { function appendStableVersionLabelToResource(files, kubectl) {
yield KubernetesManifestUtility.checkManifestStability(kubectl, resources); const manifestFiles = [];
}); const newObjectsList = [];
} files.forEach((filePath) => {
function annotateResources(files, kubectl, resourceTypes, allPods) { const fileContents = fs.readFileSync(filePath);
const annotateResults = []; yaml.safeLoadAll(fileContents, function (inputObject) {
annotateResults.push(utility_1.annotateNamespace(kubectl, TaskInputParameters.namespace)); const kind = inputObject.kind;
annotateResults.push(kubectl.annotateFiles(files, models.workflowAnnotations, true)); if (KubernetesObjectUtility.isDeploymentEntity(kind)) {
resourceTypes.forEach(resource => { const updatedObject = canaryDeploymentHelper.markResourceAsStable(inputObject);
if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) { newObjectsList.push(updatedObject);
utility_1.annotateChildPods(kubectl, resource.type, resource.name, allPods) }
.forEach(execResult => annotateResults.push(execResult)); else {
} manifestFiles.push(filePath);
}); }
utility_1.checkForErrors(annotateResults, true); });
} });
function updateResourceObjects(filePaths, imagePullSecrets, containers) { const updatedManifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
const newObjectsList = []; manifestFiles.push(...updatedManifestFiles);
const updateResourceObject = (inputObject) => { return manifestFiles;
if (!!imagePullSecrets && imagePullSecrets.length > 0) { }
KubernetesObjectUtility.updateImagePullSecrets(inputObject, imagePullSecrets, false); function checkManifestStability(kubectl, resources) {
} return __awaiter(this, void 0, void 0, function* () {
if (!!containers && containers.length > 0) { yield KubernetesManifestUtility.checkManifestStability(kubectl, resources);
KubernetesObjectUtility.updateImageDetails(inputObject, containers); });
} }
}; function annotateAndLabelResources(files, kubectl, resourceTypes, allPods) {
filePaths.forEach((filePath) => { return __awaiter(this, void 0, void 0, function* () {
const fileContents = fs.readFileSync(filePath).toString(); const workflowFilePath = yield utility_1.getWorkflowFilePath(TaskInputParameters.githubToken);
yaml.safeLoadAll(fileContents, function (inputObject) { const deploymentConfig = yield utility_1.getDeploymentConfig();
if (inputObject && inputObject.kind) { const annotationKeyLabel = models.getWorkflowAnnotationKeyLabel(workflowFilePath);
const kind = inputObject.kind; annotateResources(files, kubectl, resourceTypes, allPods, annotationKeyLabel, workflowFilePath, deploymentConfig);
if (KubernetesObjectUtility.isWorkloadEntity(kind)) { labelResources(files, kubectl, annotationKeyLabel);
updateResourceObject(inputObject); });
} }
else if (string_comparison_1.isEqual(kind, 'list', string_comparison_1.StringComparer.OrdinalIgnoreCase)) { function annotateResources(files, kubectl, resourceTypes, allPods, annotationKey, workflowFilePath, deploymentConfig) {
let items = inputObject.items; const annotateResults = [];
if (items.length > 0) { const lastSuccessSha = utility_1.getLastSuccessfulRunSha(kubectl, TaskInputParameters.namespace, annotationKey);
items.forEach((item) => updateResourceObject(item)); let annotationKeyValStr = annotationKey + '=' + models.getWorkflowAnnotationsJson(lastSuccessSha, workflowFilePath, deploymentConfig);
} annotateResults.push(kubectl.annotate('namespace', TaskInputParameters.namespace, annotationKeyValStr));
} annotateResults.push(kubectl.annotateFiles(files, annotationKeyValStr));
newObjectsList.push(inputObject); resourceTypes.forEach(resource => {
} if (resource.type.toUpperCase() !== models.KubernetesWorkload.pod.toUpperCase()) {
}); utility_1.annotateChildPods(kubectl, resource.type, resource.name, annotationKeyValStr, allPods)
}); .forEach(execResult => annotateResults.push(execResult));
core.debug('New K8s objects after adding imagePullSecrets are :' + JSON.stringify(newObjectsList)); }
const newFilePaths = fileHelper.writeObjectsToFile(newObjectsList); });
return newFilePaths; utility_1.checkForErrors(annotateResults, true);
} }
function isCanaryDeploymentStrategy(deploymentStrategy) { function labelResources(files, kubectl, label) {
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase(); let workflowName = process.env.GITHUB_WORKFLOW;
} workflowName = workflowName.startsWith('.github/workflows/') ?
workflowName.replace(".github/workflows/", "") : workflowName;
const labels = [`workflowFriendlyName=${workflowName}`, `workflow=${label}`];
utility_1.checkForErrors([kubectl.labelFiles(files, labels)], true);
}
function isCanaryDeploymentStrategy(deploymentStrategy) {
return deploymentStrategy != null && deploymentStrategy.toUpperCase() === canaryDeploymentHelper.CANARY_DEPLOYMENT_STRATEGY.toUpperCase();
}
@@ -0,0 +1,158 @@
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateIngressBackend = exports.getUpdatedBlueGreenIngress = exports.validateIngressesState = exports.routeBlueGreenIngress = exports.rejectBlueGreenIngress = exports.promoteBlueGreenIngress = exports.deployBlueGreenIngress = void 0;
const core = require("@actions/core");
const fileHelper = require("../files-helper");
const blue_green_helper_1 = require("./blue-green-helper");
const blue_green_helper_2 = require("./blue-green-helper");
const BACKEND = 'BACKEND';
function deployBlueGreenIngress(kubectl, filePaths) {
// get all kubernetes objects defined in manifest files
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
// create deployments with green label value
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.GREEN_LABEL_VALUE);
// create new services and other objects
let newObjectsList = [];
manifestObjects.serviceEntityList.forEach(inputObject => {
const newBlueGreenObject = blue_green_helper_1.getNewBlueGreenObject(inputObject, blue_green_helper_2.GREEN_LABEL_VALUE);
;
core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject));
newObjectsList.push(newBlueGreenObject);
});
newObjectsList = newObjectsList.concat(manifestObjects.otherObjects).concat(manifestObjects.unroutedServiceEntityList);
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
// return results to check for manifest stability
return result;
}
exports.deployBlueGreenIngress = deployBlueGreenIngress;
function promoteBlueGreenIngress(kubectl, manifestObjects) {
return __awaiter(this, void 0, void 0, function* () {
//checking if anything to promote
if (!validateIngressesState(kubectl, manifestObjects.ingressEntityList, manifestObjects.serviceNameMap)) {
throw ('NotInPromoteStateIngress');
}
// create stable deployments with new configuration
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.NONE_LABEL_VALUE);
// create stable services with new configuration
const newObjectsList = [];
manifestObjects.serviceEntityList.forEach((inputObject) => {
const newBlueGreenObject = blue_green_helper_1.getNewBlueGreenObject(inputObject, blue_green_helper_2.NONE_LABEL_VALUE);
core.debug('New blue-green object is: ' + JSON.stringify(newBlueGreenObject));
newObjectsList.push(newBlueGreenObject);
});
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
// returning deployments to check for rollout stability
return result;
});
}
exports.promoteBlueGreenIngress = promoteBlueGreenIngress;
function rejectBlueGreenIngress(kubectl, filePaths) {
return __awaiter(this, void 0, void 0, function* () {
// get all kubernetes objects defined in manifest files
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
// routing ingress to stables services
routeBlueGreenIngress(kubectl, null, manifestObjects.serviceNameMap, manifestObjects.ingressEntityList);
// deleting green services and deployments
blue_green_helper_1.deleteWorkloadsAndServicesWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList, manifestObjects.serviceEntityList);
});
}
exports.rejectBlueGreenIngress = rejectBlueGreenIngress;
function routeBlueGreenIngress(kubectl, nextLabel, serviceNameMap, ingressEntityList) {
let newObjectsList = [];
if (!nextLabel) {
newObjectsList = ingressEntityList.filter(ingress => isIngressRouted(ingress, serviceNameMap));
}
else {
ingressEntityList.forEach((inputObject) => {
if (isIngressRouted(inputObject, serviceNameMap)) {
const newBlueGreenIngressObject = getUpdatedBlueGreenIngress(inputObject, serviceNameMap, blue_green_helper_2.GREEN_LABEL_VALUE);
newObjectsList.push(newBlueGreenIngressObject);
}
else {
newObjectsList.push(inputObject);
}
});
}
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
}
exports.routeBlueGreenIngress = routeBlueGreenIngress;
function validateIngressesState(kubectl, ingressEntityList, serviceNameMap) {
let areIngressesTargetingNewServices = true;
ingressEntityList.forEach((inputObject) => {
if (isIngressRouted(inputObject, serviceNameMap)) {
//querying existing ingress
let existingIngress = blue_green_helper_1.fetchResource(kubectl, inputObject.kind, inputObject.metadata.name);
if (!!existingIngress) {
let currentLabel;
// checking its label
try {
currentLabel = existingIngress.metadata.labels[blue_green_helper_2.BLUE_GREEN_VERSION_LABEL];
}
catch (_a) {
// if no label exists, then not an ingress targeting green deployments
areIngressesTargetingNewServices = false;
}
if (currentLabel != blue_green_helper_2.GREEN_LABEL_VALUE) {
// if not green label, then wrong configuration
areIngressesTargetingNewServices = false;
}
}
else {
// no ingress at all, so nothing to promote
areIngressesTargetingNewServices = false;
}
}
});
return areIngressesTargetingNewServices;
}
exports.validateIngressesState = validateIngressesState;
function isIngressRouted(ingressObject, serviceNameMap) {
let isIngressRouted = false;
// sees if ingress targets a service in the given manifests
JSON.parse(JSON.stringify(ingressObject), (key, value) => {
if (key === 'serviceName' && serviceNameMap.has(value)) {
isIngressRouted = true;
}
return value;
});
return isIngressRouted;
}
function getUpdatedBlueGreenIngress(inputObject, serviceNameMap, type) {
if (!type) {
// returning original with no modifications
return inputObject;
}
const newObject = JSON.parse(JSON.stringify(inputObject));
// adding green labels and values
blue_green_helper_1.addBlueGreenLabelsAndAnnotations(newObject, type);
// Updating ingress labels
let finalObject = updateIngressBackend(newObject, serviceNameMap);
return finalObject;
}
exports.getUpdatedBlueGreenIngress = getUpdatedBlueGreenIngress;
function updateIngressBackend(inputObject, serviceNameMap) {
inputObject = JSON.parse(JSON.stringify(inputObject), (key, value) => {
if (key.toUpperCase() === BACKEND) {
let serviceName = value.serviceName;
if (serviceNameMap.has(serviceName)) {
// updating service name with corresponding bluegreen name only if service is provied in given manifests
value.serviceName = serviceNameMap.get(serviceName);
}
}
return value;
});
return inputObject;
}
exports.updateIngressBackend = updateIngressBackend;
@@ -1,58 +1,58 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.deployPodCanary = void 0; exports.deployPodCanary = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const fileHelper = require("../files-helper"); const fileHelper = require("../files-helper");
const helper = require("../resource-object-utility"); const helper = require("../resource-object-utility");
const canaryDeploymentHelper = require("./canary-deployment-helper"); const canaryDeploymentHelper = require("./canary-deployment-helper");
function deployPodCanary(kubectl, filePaths) { function deployPodCanary(kubectl, filePaths) {
const newObjectsList = []; const newObjectsList = [];
const percentage = parseInt(TaskInputParameters.canaryPercentage); const percentage = parseInt(TaskInputParameters.canaryPercentage);
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isDeploymentEntity(kind)) { if (helper.isDeploymentEntity(kind)) {
core.debug('Calculating replica count for canary'); core.debug('Calculating replica count for canary');
const canaryReplicaCount = calculateReplicaCountForCanary(inputObject, percentage); const canaryReplicaCount = calculateReplicaCountForCanary(inputObject, percentage);
core.debug('Replica count is ' + canaryReplicaCount); core.debug('Replica count is ' + canaryReplicaCount);
// Get stable object // Get stable object
core.debug('Querying stable object'); core.debug('Querying stable object');
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name); const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
if (!stableObject) { if (!stableObject) {
core.debug('Stable object not found. Creating only canary object'); core.debug('Stable object not found. Creating only canary object');
// If stable object not found, create canary deployment. // If stable object not found, create canary deployment.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
} }
else { else {
core.debug('Stable object found. Creating canary and baseline objects'); core.debug('Stable object found. Creating canary and baseline objects');
// If canary object not found, create canary and baseline object. // If canary object not found, create canary and baseline object.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount); const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject)); core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
newObjectsList.push(newBaselineObject); newObjectsList.push(newBaselineObject);
} }
} }
else { else {
// Updating non deployment entity as it is. // Updating non deployment entity as it is.
newObjectsList.push(inputObject); newObjectsList.push(inputObject);
} }
}); });
}); });
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment); const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
return { 'result': result, 'newFilePaths': manifestFiles }; return { 'result': result, 'newFilePaths': manifestFiles };
} }
exports.deployPodCanary = deployPodCanary; exports.deployPodCanary = deployPodCanary;
function calculateReplicaCountForCanary(inputObject, percentage) { function calculateReplicaCountForCanary(inputObject, percentage) {
const inputReplicaCount = helper.getReplicaCount(inputObject); const inputReplicaCount = helper.getReplicaCount(inputObject);
return Math.round((inputReplicaCount * percentage) / 100); return Math.round((inputReplicaCount * percentage) / 100);
} }
@@ -0,0 +1,97 @@
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getServiceSpecLabel = exports.validateServicesState = exports.routeBlueGreenService = exports.rejectBlueGreenService = exports.promoteBlueGreenService = exports.deployBlueGreenService = void 0;
const fileHelper = require("../files-helper");
const blue_green_helper_1 = require("./blue-green-helper");
const blue_green_helper_2 = require("./blue-green-helper");
function deployBlueGreenService(kubectl, filePaths) {
// get all kubernetes objects defined in manifest files
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
// create deployments with green label value
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.GREEN_LABEL_VALUE);
// create other non deployment and non service entities
const newObjectsList = manifestObjects.otherObjects.concat(manifestObjects.ingressEntityList).concat(manifestObjects.unroutedServiceEntityList);
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
// returning deployment details to check for rollout stability
return result;
}
exports.deployBlueGreenService = deployBlueGreenService;
function promoteBlueGreenService(kubectl, manifestObjects) {
return __awaiter(this, void 0, void 0, function* () {
// checking if services are in the right state ie. targeting green deployments
if (!validateServicesState(kubectl, manifestObjects.serviceEntityList)) {
throw ('NotInPromoteState');
}
// creating stable deployments with new configurations
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.NONE_LABEL_VALUE);
// returning deployment details to check for rollout stability
return result;
});
}
exports.promoteBlueGreenService = promoteBlueGreenService;
function rejectBlueGreenService(kubectl, filePaths) {
return __awaiter(this, void 0, void 0, function* () {
// get all kubernetes objects defined in manifest files
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
// routing to stable objects
routeBlueGreenService(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
// deleting the new deployments with green suffix
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
});
}
exports.rejectBlueGreenService = rejectBlueGreenService;
function routeBlueGreenService(kubectl, nextLabel, serviceEntityList) {
const newObjectsList = [];
serviceEntityList.forEach((serviceObject) => {
const newBlueGreenServiceObject = getUpdatedBlueGreenService(serviceObject, nextLabel);
newObjectsList.push(newBlueGreenServiceObject);
});
// configures the services
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
}
exports.routeBlueGreenService = routeBlueGreenService;
// adding green labels to configure existing service
function getUpdatedBlueGreenService(inputObject, labelValue) {
const newObject = JSON.parse(JSON.stringify(inputObject));
// Adding labels and annotations.
blue_green_helper_1.addBlueGreenLabelsAndAnnotations(newObject, labelValue);
return newObject;
}
function validateServicesState(kubectl, serviceEntityList) {
let areServicesGreen = true;
serviceEntityList.forEach((serviceObject) => {
// finding the existing routed service
const existingService = blue_green_helper_1.fetchResource(kubectl, serviceObject.kind, serviceObject.metadata.name);
if (!!existingService) {
let currentLabel = getServiceSpecLabel(existingService);
if (currentLabel != blue_green_helper_2.GREEN_LABEL_VALUE) {
// service should be targeting deployments with green label
areServicesGreen = false;
}
}
else {
// service targeting deployment doesn't exist
areServicesGreen = false;
}
});
return areServicesGreen;
}
exports.validateServicesState = validateServicesState;
function getServiceSpecLabel(inputObject) {
if (!!inputObject && inputObject.spec && inputObject.spec.selector && inputObject.spec.selector[blue_green_helper_2.BLUE_GREEN_VERSION_LABEL]) {
return inputObject.spec.selector[blue_green_helper_2.BLUE_GREEN_VERSION_LABEL];
}
return '';
}
exports.getServiceSpecLabel = getServiceSpecLabel;
@@ -0,0 +1,184 @@
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanupSMI = exports.validateTrafficSplitsState = exports.routeBlueGreenSMI = exports.getSMIServiceResource = exports.setupSMI = exports.rejectBlueGreenSMI = exports.promoteBlueGreenSMI = exports.deployBlueGreenSMI = void 0;
const kubectlUtils = require("../kubectl-util");
const fileHelper = require("../files-helper");
const blue_green_helper_1 = require("./blue-green-helper");
const blue_green_helper_2 = require("./blue-green-helper");
let trafficSplitAPIVersion = "";
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-trafficsplit';
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit';
const MIN_VAL = '0';
const MAX_VAL = '100';
function deployBlueGreenSMI(kubectl, filePaths) {
// get all kubernetes objects defined in manifest files
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
// creating services and other objects
const newObjectsList = manifestObjects.otherObjects.concat(manifestObjects.serviceEntityList).concat(manifestObjects.ingressEntityList).concat(manifestObjects.unroutedServiceEntityList);
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
// make extraservices and trafficsplit
setupSMI(kubectl, manifestObjects.serviceEntityList);
// create new deloyments
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.GREEN_LABEL_VALUE);
// return results to check for manifest stability
return result;
}
exports.deployBlueGreenSMI = deployBlueGreenSMI;
function promoteBlueGreenSMI(kubectl, manifestObjects) {
return __awaiter(this, void 0, void 0, function* () {
// checking if there is something to promote
if (!validateTrafficSplitsState(kubectl, manifestObjects.serviceEntityList)) {
throw ('NotInPromoteStateSMI');
}
// create stable deployments with new configuration
const result = blue_green_helper_1.createWorkloadsWithLabel(kubectl, manifestObjects.deploymentEntityList, blue_green_helper_2.NONE_LABEL_VALUE);
// return result to check for stability
return result;
});
}
exports.promoteBlueGreenSMI = promoteBlueGreenSMI;
function rejectBlueGreenSMI(kubectl, filePaths) {
return __awaiter(this, void 0, void 0, function* () {
// get all kubernetes objects defined in manifest files
const manifestObjects = blue_green_helper_1.getManifestObjects(filePaths);
// routing trafficsplit to stable deploymetns
routeBlueGreenSMI(kubectl, blue_green_helper_2.NONE_LABEL_VALUE, manifestObjects.serviceEntityList);
// deleting rejected new bluegreen deplyments
blue_green_helper_1.deleteWorkloadsWithLabel(kubectl, blue_green_helper_2.GREEN_LABEL_VALUE, manifestObjects.deploymentEntityList);
//deleting trafficsplit and extra services
cleanupSMI(kubectl, manifestObjects.serviceEntityList);
});
}
exports.rejectBlueGreenSMI = rejectBlueGreenSMI;
function setupSMI(kubectl, serviceEntityList) {
const newObjectsList = [];
const trafficObjectList = [];
serviceEntityList.forEach((serviceObject) => {
// create a trafficsplit for service
trafficObjectList.push(serviceObject);
// setting up the services for trafficsplit
const newStableService = getSMIServiceResource(serviceObject, blue_green_helper_2.STABLE_SUFFIX);
const newGreenService = getSMIServiceResource(serviceObject, blue_green_helper_2.GREEN_SUFFIX);
newObjectsList.push(newStableService);
newObjectsList.push(newGreenService);
});
// creating services
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
kubectl.apply(manifestFiles);
// route to stable service
trafficObjectList.forEach((inputObject) => {
createTrafficSplitObject(kubectl, inputObject.metadata.name, blue_green_helper_2.NONE_LABEL_VALUE);
});
}
exports.setupSMI = setupSMI;
function createTrafficSplitObject(kubectl, name, nextLabel) {
// getting smi spec api version
if (!trafficSplitAPIVersion) {
trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl);
}
// deciding weights based on nextlabel
let stableWeight;
let greenWeight;
if (nextLabel === blue_green_helper_2.GREEN_LABEL_VALUE) {
stableWeight = parseInt(MIN_VAL);
greenWeight = parseInt(MAX_VAL);
}
else {
stableWeight = parseInt(MAX_VAL);
greenWeight = parseInt(MIN_VAL);
}
//traffic split json
const trafficSplitObject = `{
"apiVersion": "${trafficSplitAPIVersion}",
"kind": "TrafficSplit",
"metadata": {
"name": "${blue_green_helper_1.getBlueGreenResourceName(name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX)}"
},
"spec": {
"service": "${name}",
"backends": [
{
"service": "${blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.STABLE_SUFFIX)}",
"weight": ${stableWeight}
},
{
"service": "${blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.GREEN_SUFFIX)}",
"weight": ${greenWeight}
}
]
}
}`;
// creating trafficplit object
const trafficSplitManifestFile = fileHelper.writeManifestToFile(trafficSplitObject, TRAFFIC_SPLIT_OBJECT, blue_green_helper_1.getBlueGreenResourceName(name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX));
kubectl.apply(trafficSplitManifestFile);
}
function getSMIServiceResource(inputObject, suffix) {
const newObject = JSON.parse(JSON.stringify(inputObject));
if (suffix === blue_green_helper_2.STABLE_SUFFIX) {
// adding stable suffix to service name
newObject.metadata.name = blue_green_helper_1.getBlueGreenResourceName(inputObject.metadata.name, blue_green_helper_2.STABLE_SUFFIX);
return blue_green_helper_1.getNewBlueGreenObject(newObject, blue_green_helper_2.NONE_LABEL_VALUE);
}
else {
// green label will be added for these
return blue_green_helper_1.getNewBlueGreenObject(newObject, blue_green_helper_2.GREEN_LABEL_VALUE);
}
}
exports.getSMIServiceResource = getSMIServiceResource;
function routeBlueGreenSMI(kubectl, nextLabel, serviceEntityList) {
serviceEntityList.forEach((serviceObject) => {
// routing trafficsplit to given label
createTrafficSplitObject(kubectl, serviceObject.metadata.name, nextLabel);
});
}
exports.routeBlueGreenSMI = routeBlueGreenSMI;
function validateTrafficSplitsState(kubectl, serviceEntityList) {
let areTrafficSplitsInRightState = true;
serviceEntityList.forEach((serviceObject) => {
const name = serviceObject.metadata.name;
let trafficSplitObject = blue_green_helper_1.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, blue_green_helper_1.getBlueGreenResourceName(name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX));
if (!trafficSplitObject) {
// no trafficplit exits
areTrafficSplitsInRightState = false;
}
trafficSplitObject = JSON.parse(JSON.stringify(trafficSplitObject));
trafficSplitObject.spec.backends.forEach(element => {
// checking if trafficsplit in right state to deploy
if (element.service === blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.GREEN_SUFFIX)) {
if (element.weight != MAX_VAL) {
// green service should have max weight
areTrafficSplitsInRightState = false;
}
}
if (element.service === blue_green_helper_1.getBlueGreenResourceName(name, blue_green_helper_2.STABLE_SUFFIX)) {
if (element.weight != MIN_VAL) {
// stable service should have 0 weight
areTrafficSplitsInRightState = false;
}
}
});
});
return areTrafficSplitsInRightState;
}
exports.validateTrafficSplitsState = validateTrafficSplitsState;
function cleanupSMI(kubectl, serviceEntityList) {
const deleteList = [];
serviceEntityList.forEach((serviceObject) => {
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX), kind: TRAFFIC_SPLIT_OBJECT });
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, blue_green_helper_2.GREEN_SUFFIX), kind: serviceObject.kind });
deleteList.push({ name: blue_green_helper_1.getBlueGreenResourceName(serviceObject.metadata.name, blue_green_helper_2.STABLE_SUFFIX), kind: serviceObject.kind });
});
// deleting all objects
blue_green_helper_1.deleteObjects(kubectl, deleteList);
}
exports.cleanupSMI = cleanupSMI;
@@ -1,172 +1,172 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.redirectTrafficToStableDeployment = exports.redirectTrafficToCanaryDeployment = exports.deploySMICanary = void 0; exports.redirectTrafficToStableDeployment = exports.redirectTrafficToCanaryDeployment = exports.deploySMICanary = void 0;
const core = require("@actions/core"); const core = require("@actions/core");
const fs = require("fs"); const fs = require("fs");
const yaml = require("js-yaml"); const yaml = require("js-yaml");
const util = require("util"); const util = require("util");
const TaskInputParameters = require("../../input-parameters"); const TaskInputParameters = require("../../input-parameters");
const fileHelper = require("../files-helper"); const fileHelper = require("../files-helper");
const helper = require("../resource-object-utility"); const helper = require("../resource-object-utility");
const utils = require("../manifest-utilities"); const utils = require("../manifest-utilities");
const kubectlUtils = require("../kubectl-util"); const kubectlUtils = require("../kubectl-util");
const canaryDeploymentHelper = require("./canary-deployment-helper"); const canaryDeploymentHelper = require("./canary-deployment-helper");
const utility_1 = require("../utility"); const utility_1 = require("../utility");
const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout'; const TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX = '-workflow-rollout';
const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit'; const TRAFFIC_SPLIT_OBJECT = 'TrafficSplit';
let trafficSplitAPIVersion = ""; let trafficSplitAPIVersion = "";
function deploySMICanary(kubectl, filePaths) { function deploySMICanary(kubectl, filePaths) {
const newObjectsList = []; const newObjectsList = [];
const canaryReplicaCount = parseInt(TaskInputParameters.baselineAndCanaryReplicas); const canaryReplicaCount = parseInt(TaskInputParameters.baselineAndCanaryReplicas);
core.debug('Replica count is ' + canaryReplicaCount); core.debug('Replica count is ' + canaryReplicaCount);
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isDeploymentEntity(kind)) { if (helper.isDeploymentEntity(kind)) {
// Get stable object // Get stable object
core.debug('Querying stable object'); core.debug('Querying stable object');
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name); const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, name);
if (!stableObject) { if (!stableObject) {
core.debug('Stable object not found. Creating only canary object'); core.debug('Stable object not found. Creating only canary object');
// If stable object not found, create canary deployment. // If stable object not found, create canary deployment.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
} }
else { else {
if (!canaryDeploymentHelper.isResourceMarkedAsStable(stableObject)) { if (!canaryDeploymentHelper.isResourceMarkedAsStable(stableObject)) {
throw (`StableSpecSelectorNotExist : ${name}`); throw (`StableSpecSelectorNotExist : ${name}`);
} }
core.debug('Stable object found. Creating canary and baseline objects'); core.debug('Stable object found. Creating canary and baseline objects');
// If canary object not found, create canary and baseline object. // If canary object not found, create canary and baseline object.
const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount); const newCanaryObject = canaryDeploymentHelper.getNewCanaryResource(inputObject, canaryReplicaCount);
const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount); const newBaselineObject = canaryDeploymentHelper.getNewBaselineResource(stableObject, canaryReplicaCount);
core.debug('New canary object is: ' + JSON.stringify(newCanaryObject)); core.debug('New canary object is: ' + JSON.stringify(newCanaryObject));
core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject)); core.debug('New baseline object is: ' + JSON.stringify(newBaselineObject));
newObjectsList.push(newCanaryObject); newObjectsList.push(newCanaryObject);
newObjectsList.push(newBaselineObject); newObjectsList.push(newBaselineObject);
} }
} }
else { else {
// Updating non deployment entity as it is. // Updating non deployment entity as it is.
newObjectsList.push(inputObject); newObjectsList.push(inputObject);
} }
}); });
}); });
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment); const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
createCanaryService(kubectl, filePaths); createCanaryService(kubectl, filePaths);
return { 'result': result, 'newFilePaths': manifestFiles }; return { 'result': result, 'newFilePaths': manifestFiles };
} }
exports.deploySMICanary = deploySMICanary; exports.deploySMICanary = deploySMICanary;
function createCanaryService(kubectl, filePaths) { function createCanaryService(kubectl, filePaths) {
const newObjectsList = []; const newObjectsList = [];
const trafficObjectsList = []; const trafficObjectsList = [];
filePaths.forEach((filePath) => { filePaths.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isServiceEntity(kind)) { if (helper.isServiceEntity(kind)) {
const newCanaryServiceObject = canaryDeploymentHelper.getNewCanaryResource(inputObject); const newCanaryServiceObject = canaryDeploymentHelper.getNewCanaryResource(inputObject);
core.debug('New canary service object is: ' + JSON.stringify(newCanaryServiceObject)); core.debug('New canary service object is: ' + JSON.stringify(newCanaryServiceObject));
newObjectsList.push(newCanaryServiceObject); newObjectsList.push(newCanaryServiceObject);
const newBaselineServiceObject = canaryDeploymentHelper.getNewBaselineResource(inputObject); const newBaselineServiceObject = canaryDeploymentHelper.getNewBaselineResource(inputObject);
core.debug('New baseline object is: ' + JSON.stringify(newBaselineServiceObject)); core.debug('New baseline object is: ' + JSON.stringify(newBaselineServiceObject));
newObjectsList.push(newBaselineServiceObject); newObjectsList.push(newBaselineServiceObject);
core.debug('Querying for stable service object'); core.debug('Querying for stable service object');
const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, canaryDeploymentHelper.getStableResourceName(name)); const stableObject = canaryDeploymentHelper.fetchResource(kubectl, kind, canaryDeploymentHelper.getStableResourceName(name));
if (!stableObject) { if (!stableObject) {
const newStableServiceObject = canaryDeploymentHelper.getStableResource(inputObject); const newStableServiceObject = canaryDeploymentHelper.getStableResource(inputObject);
core.debug('New stable service object is: ' + JSON.stringify(newStableServiceObject)); core.debug('New stable service object is: ' + JSON.stringify(newStableServiceObject));
newObjectsList.push(newStableServiceObject); newObjectsList.push(newStableServiceObject);
core.debug('Creating the traffic object for service: ' + name); core.debug('Creating the traffic object for service: ' + name);
const trafficObject = createTrafficSplitManifestFile(kubectl, name, 0, 0, 1000); const trafficObject = createTrafficSplitManifestFile(kubectl, name, 0, 0, 1000);
core.debug('Creating the traffic object for service: ' + trafficObject); core.debug('Creating the traffic object for service: ' + trafficObject);
trafficObjectsList.push(trafficObject); trafficObjectsList.push(trafficObject);
} }
else { else {
let updateTrafficObject = true; let updateTrafficObject = true;
const trafficObject = canaryDeploymentHelper.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, getTrafficSplitResourceName(name)); const trafficObject = canaryDeploymentHelper.fetchResource(kubectl, TRAFFIC_SPLIT_OBJECT, getTrafficSplitResourceName(name));
if (trafficObject) { if (trafficObject) {
const trafficJObject = JSON.parse(JSON.stringify(trafficObject)); const trafficJObject = JSON.parse(JSON.stringify(trafficObject));
if (trafficJObject && trafficJObject.spec && trafficJObject.spec.backends) { if (trafficJObject && trafficJObject.spec && trafficJObject.spec.backends) {
trafficJObject.spec.backends.forEach((s) => { trafficJObject.spec.backends.forEach((s) => {
if (s.service === canaryDeploymentHelper.getCanaryResourceName(name) && s.weight === "1000m") { if (s.service === canaryDeploymentHelper.getCanaryResourceName(name) && s.weight === "1000m") {
core.debug('Update traffic objcet not required'); core.debug('Update traffic objcet not required');
updateTrafficObject = false; updateTrafficObject = false;
} }
}); });
} }
} }
if (updateTrafficObject) { if (updateTrafficObject) {
core.debug('Stable service object present so updating the traffic object for service: ' + name); core.debug('Stable service object present so updating the traffic object for service: ' + name);
trafficObjectsList.push(updateTrafficSplitObject(kubectl, name)); trafficObjectsList.push(updateTrafficSplitObject(kubectl, name));
} }
} }
} }
}); });
}); });
const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList); const manifestFiles = fileHelper.writeObjectsToFile(newObjectsList);
manifestFiles.push(...trafficObjectsList); manifestFiles.push(...trafficObjectsList);
const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment); const result = kubectl.apply(manifestFiles, TaskInputParameters.forceDeployment);
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
} }
function redirectTrafficToCanaryDeployment(kubectl, manifestFilePaths) { function redirectTrafficToCanaryDeployment(kubectl, manifestFilePaths) {
adjustTraffic(kubectl, manifestFilePaths, 0, 1000); adjustTraffic(kubectl, manifestFilePaths, 0, 1000);
} }
exports.redirectTrafficToCanaryDeployment = redirectTrafficToCanaryDeployment; exports.redirectTrafficToCanaryDeployment = redirectTrafficToCanaryDeployment;
function redirectTrafficToStableDeployment(kubectl, manifestFilePaths) { function redirectTrafficToStableDeployment(kubectl, manifestFilePaths) {
adjustTraffic(kubectl, manifestFilePaths, 1000, 0); adjustTraffic(kubectl, manifestFilePaths, 1000, 0);
} }
exports.redirectTrafficToStableDeployment = redirectTrafficToStableDeployment; exports.redirectTrafficToStableDeployment = redirectTrafficToStableDeployment;
function adjustTraffic(kubectl, manifestFilePaths, stableWeight, canaryWeight) { function adjustTraffic(kubectl, manifestFilePaths, stableWeight, canaryWeight) {
// get manifest files // get manifest files
const inputManifestFiles = utils.getManifestFiles(manifestFilePaths); const inputManifestFiles = utils.getManifestFiles(manifestFilePaths);
if (inputManifestFiles == null || inputManifestFiles.length == 0) { if (inputManifestFiles == null || inputManifestFiles.length == 0) {
return; return;
} }
const trafficSplitManifests = []; const trafficSplitManifests = [];
const serviceObjects = []; const serviceObjects = [];
inputManifestFiles.forEach((filePath) => { inputManifestFiles.forEach((filePath) => {
const fileContents = fs.readFileSync(filePath); const fileContents = fs.readFileSync(filePath);
yaml.safeLoadAll(fileContents, function (inputObject) { yaml.safeLoadAll(fileContents, function (inputObject) {
const name = inputObject.metadata.name; const name = inputObject.metadata.name;
const kind = inputObject.kind; const kind = inputObject.kind;
if (helper.isServiceEntity(kind)) { if (helper.isServiceEntity(kind)) {
trafficSplitManifests.push(createTrafficSplitManifestFile(kubectl, name, stableWeight, 0, canaryWeight)); trafficSplitManifests.push(createTrafficSplitManifestFile(kubectl, name, stableWeight, 0, canaryWeight));
serviceObjects.push(name); serviceObjects.push(name);
} }
}); });
}); });
if (trafficSplitManifests.length <= 0) { if (trafficSplitManifests.length <= 0) {
return; return;
} }
const result = kubectl.apply(trafficSplitManifests, TaskInputParameters.forceDeployment); const result = kubectl.apply(trafficSplitManifests, TaskInputParameters.forceDeployment);
core.debug('serviceObjects:' + serviceObjects.join(',') + ' result:' + result); core.debug('serviceObjects:' + serviceObjects.join(',') + ' result:' + result);
utility_1.checkForErrors([result]); utility_1.checkForErrors([result]);
} }
function updateTrafficSplitObject(kubectl, serviceName) { function updateTrafficSplitObject(kubectl, serviceName) {
const percentage = parseInt(TaskInputParameters.canaryPercentage) * 10; const percentage = parseInt(TaskInputParameters.canaryPercentage) * 10;
const baselineAndCanaryWeight = percentage / 2; const baselineAndCanaryWeight = percentage / 2;
const stableDeploymentWeight = 1000 - percentage; const stableDeploymentWeight = 1000 - percentage;
core.debug('Creating the traffic object with canary weight: ' + baselineAndCanaryWeight + ',baseling weight: ' + baselineAndCanaryWeight + ',stable: ' + stableDeploymentWeight); core.debug('Creating the traffic object with canary weight: ' + baselineAndCanaryWeight + ',baseling weight: ' + baselineAndCanaryWeight + ',stable: ' + stableDeploymentWeight);
return createTrafficSplitManifestFile(kubectl, serviceName, stableDeploymentWeight, baselineAndCanaryWeight, baselineAndCanaryWeight); return createTrafficSplitManifestFile(kubectl, serviceName, stableDeploymentWeight, baselineAndCanaryWeight, baselineAndCanaryWeight);
} }
function createTrafficSplitManifestFile(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight) { function createTrafficSplitManifestFile(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight) {
const smiObjectString = getTrafficSplitObject(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight); const smiObjectString = getTrafficSplitObject(kubectl, serviceName, stableWeight, baselineWeight, canaryWeight);
const manifestFile = fileHelper.writeManifestToFile(smiObjectString, TRAFFIC_SPLIT_OBJECT, serviceName); const manifestFile = fileHelper.writeManifestToFile(smiObjectString, TRAFFIC_SPLIT_OBJECT, serviceName);
if (!manifestFile) { if (!manifestFile) {
throw new Error('UnableToCreateTrafficSplitManifestFile'); throw new Error('UnableToCreateTrafficSplitManifestFile');
} }
return manifestFile; return manifestFile;
} }
function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, canaryWeight) { function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, canaryWeight) {
if (!trafficSplitAPIVersion) { if (!trafficSplitAPIVersion) {
trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl); trafficSplitAPIVersion = kubectlUtils.getTrafficSplitAPIVersion(kubectl);
} }
const trafficSplitObjectJson = `{ const trafficSplitObjectJson = `{
"apiVersion": "${trafficSplitAPIVersion}", "apiVersion": "${trafficSplitAPIVersion}",
"kind": "TrafficSplit", "kind": "TrafficSplit",
@@ -190,10 +190,10 @@ function getTrafficSplitObject(kubectl, name, stableWeight, baselineWeight, cana
], ],
"service": "%s" "service": "%s"
} }
}`; }`;
const trafficSplitObject = util.format(trafficSplitObjectJson, getTrafficSplitResourceName(name), canaryDeploymentHelper.getStableResourceName(name), stableWeight, canaryDeploymentHelper.getBaselineResourceName(name), baselineWeight, canaryDeploymentHelper.getCanaryResourceName(name), canaryWeight, name); const trafficSplitObject = util.format(trafficSplitObjectJson, getTrafficSplitResourceName(name), canaryDeploymentHelper.getStableResourceName(name), stableWeight, canaryDeploymentHelper.getBaselineResourceName(name), baselineWeight, canaryDeploymentHelper.getCanaryResourceName(name), canaryWeight, name);
return trafficSplitObject; return trafficSplitObject;
} }
function getTrafficSplitResourceName(name) { function getTrafficSplitResourceName(name) {
return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX; return name + TRAFFIC_SPLIT_OBJECT_NAME_SUFFIX;
} }
+26 -26
View File
@@ -1,26 +1,26 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.isEqual = exports.StringComparer = void 0; exports.isEqual = exports.StringComparer = void 0;
var StringComparer; var StringComparer;
(function (StringComparer) { (function (StringComparer) {
StringComparer[StringComparer["Ordinal"] = 0] = "Ordinal"; StringComparer[StringComparer["Ordinal"] = 0] = "Ordinal";
StringComparer[StringComparer["OrdinalIgnoreCase"] = 1] = "OrdinalIgnoreCase"; StringComparer[StringComparer["OrdinalIgnoreCase"] = 1] = "OrdinalIgnoreCase";
})(StringComparer = exports.StringComparer || (exports.StringComparer = {})); })(StringComparer = exports.StringComparer || (exports.StringComparer = {}));
function isEqual(str1, str2, stringComparer) { function isEqual(str1, str2, stringComparer) {
if (str1 == null && str2 == null) { if (str1 == null && str2 == null) {
return true; return true;
} }
if (str1 == null) { if (str1 == null) {
return false; return false;
} }
if (str2 == null) { if (str2 == null) {
return false; return false;
} }
if (stringComparer == StringComparer.OrdinalIgnoreCase) { if (stringComparer == StringComparer.OrdinalIgnoreCase) {
return str1.toUpperCase() === str2.toUpperCase(); return str1.toUpperCase() === str2.toUpperCase();
} }
else { else {
return str1 === str2; return str1 === str2;
} }
} }
exports.isEqual = isEqual; exports.isEqual = isEqual;
File diff suppressed because it is too large Load Diff
+222 -105
View File
@@ -1,105 +1,222 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.annotateNamespace = exports.annotateChildPods = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0; function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
const os = require("os"); return new (P || (P = Promise))(function (resolve, reject) {
const core = require("@actions/core"); function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
const constants_1 = require("../constants"); function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function getExecutableExtension() { function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
if (os.type().match(/^Win/)) { step((generator = generator.apply(thisArg, _arguments || [])).next());
return '.exe'; });
} };
return ''; Object.defineProperty(exports, "__esModule", { value: true });
} exports.getNormalizedPath = exports.isHttpUrl = exports.getCurrentTime = exports.getRandomInt = exports.sleep = exports.getDeploymentConfig = exports.annotateChildPods = exports.getWorkflowFilePath = exports.getLastSuccessfulRunSha = exports.checkForErrors = exports.isEqual = exports.getExecutableExtension = void 0;
exports.getExecutableExtension = getExecutableExtension; const os = require("os");
function isEqual(str1, str2, ignoreCase) { const core = require("@actions/core");
if (str1 == null && str2 == null) { const githubClient_1 = require("../githubClient");
return true; const httpClient_1 = require("./httpClient");
} const inputParams = require("../input-parameters");
if (str1 == null || str2 == null) { const docker_object_model_1 = require("../docker-object-model");
return false; const io = require("@actions/io");
} function getExecutableExtension() {
if (ignoreCase) { if (os.type().match(/^Win/)) {
return str1.toUpperCase() === str2.toUpperCase(); return '.exe';
} }
else { return '';
return str1 === str2; }
} exports.getExecutableExtension = getExecutableExtension;
} function isEqual(str1, str2, ignoreCase) {
exports.isEqual = isEqual; if (str1 == null && str2 == null) {
function checkForErrors(execResults, warnIfError) { return true;
if (execResults.length !== 0) { }
let stderr = ''; if (str1 == null || str2 == null) {
execResults.forEach(result => { return false;
if (result && result.stderr) { }
if (result.code !== 0) { if (ignoreCase) {
stderr += result.stderr + '\n'; return str1.toUpperCase() === str2.toUpperCase();
} }
else { else {
core.warning(result.stderr); return str1 === str2;
} }
} }
}); exports.isEqual = isEqual;
if (stderr.length > 0) { function checkForErrors(execResults, warnIfError) {
if (warnIfError) { if (execResults.length !== 0) {
core.warning(stderr.trim()); let stderr = '';
} execResults.forEach(result => {
else { if (result && result.stderr) {
throw new Error(stderr.trim()); if (result.code !== 0) {
} stderr += result.stderr + '\n';
} }
} else {
} core.warning(result.stderr);
exports.checkForErrors = checkForErrors; }
function annotateChildPods(kubectl, resourceType, resourceName, allPods) { }
const commandExecutionResults = []; });
let owner = resourceName; if (stderr.length > 0) {
if (resourceType.toLowerCase().indexOf('deployment') > -1) { if (warnIfError) {
owner = kubectl.getNewReplicaSet(resourceName); core.warning(stderr.trim());
} }
if (allPods && allPods.items && allPods.items.length > 0) { else {
allPods.items.forEach((pod) => { throw new Error(stderr.trim());
const owners = pod.metadata.ownerReferences; }
if (owners) { }
owners.forEach(ownerRef => { }
if (ownerRef.name === owner) { }
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, constants_1.workflowAnnotations, true)); exports.checkForErrors = checkForErrors;
} function getLastSuccessfulRunSha(kubectl, namespaceName, annotationKey) {
}); try {
} const result = kubectl.getResource('namespace', namespaceName);
}); if (result) {
} if (result.stderr) {
return commandExecutionResults; core.warning(`${result.stderr}`);
} return process.env.GITHUB_SHA;
exports.annotateChildPods = annotateChildPods; }
function annotateNamespace(kubectl, namespaceName) { else if (result.stdout) {
const result = kubectl.getResource('namespace', namespaceName); const annotationsSet = JSON.parse(result.stdout).metadata.annotations;
if (!result) { if (annotationsSet && annotationsSet[annotationKey]) {
return { code: -1, stderr: 'Failed to get resource' }; return JSON.parse(annotationsSet[annotationKey].replace(/'/g, '"')).commit;
} }
else if (result && result.stderr) { else {
return result; return 'NA';
} }
if (result && result.stdout) { }
const annotationsSet = JSON.parse(result.stdout).metadata.annotations; }
if (annotationsSet && annotationsSet.runUri) { }
if (annotationsSet.runUri.indexOf(process.env['GITHUB_REPOSITORY']) == -1) { catch (ex) {
core.debug(`Skipping 'annotate namespace' as namespace annotated by other workflow`); core.warning(`Failed to get commits from cluster. ${JSON.stringify(ex)}`);
return { code: 0, stdout: '' }; return '';
} }
} }
return kubectl.annotate('namespace', namespaceName, constants_1.workflowAnnotations, true); exports.getLastSuccessfulRunSha = getLastSuccessfulRunSha;
} function getWorkflowFilePath(githubToken) {
} return __awaiter(this, void 0, void 0, function* () {
exports.annotateNamespace = annotateNamespace; let workflowFilePath = process.env.GITHUB_WORKFLOW;
function sleep(timeout) { if (!workflowFilePath.startsWith('.github/workflows/')) {
return new Promise(resolve => setTimeout(resolve, timeout)); const githubClient = new githubClient_1.GitHubClient(process.env.GITHUB_REPOSITORY, githubToken);
} const response = yield githubClient.getWorkflows();
exports.sleep = sleep; if (response) {
function getRandomInt(max) { if (response.statusCode == httpClient_1.StatusCodes.OK
return Math.floor(Math.random() * Math.floor(max)); && response.body
} && response.body.total_count) {
exports.getRandomInt = getRandomInt; if (response.body.total_count > 0) {
function getCurrentTime() { for (let workflow of response.body.workflows) {
return new Date().getTime(); if (process.env.GITHUB_WORKFLOW === workflow.name) {
} workflowFilePath = workflow.path;
exports.getCurrentTime = getCurrentTime; break;
}
}
}
}
else if (response.statusCode != httpClient_1.StatusCodes.OK) {
core.debug(`An error occured while getting list of workflows on the repo. Statuscode: ${response.statusCode}, StatusMessage: ${response.statusMessage}`);
}
}
else {
core.warning(`Failed to get response from workflow list API`);
}
}
return Promise.resolve(workflowFilePath);
});
}
exports.getWorkflowFilePath = getWorkflowFilePath;
function annotateChildPods(kubectl, resourceType, resourceName, annotationKeyValStr, allPods) {
const commandExecutionResults = [];
let owner = resourceName;
if (resourceType.toLowerCase().indexOf('deployment') > -1) {
owner = kubectl.getNewReplicaSet(resourceName);
}
if (allPods && allPods.items && allPods.items.length > 0) {
allPods.items.forEach((pod) => {
const owners = pod.metadata.ownerReferences;
if (owners) {
for (let ownerRef of owners) {
if (ownerRef.name === owner) {
commandExecutionResults.push(kubectl.annotate('pod', pod.metadata.name, annotationKeyValStr));
break;
}
}
}
});
}
return commandExecutionResults;
}
exports.annotateChildPods = annotateChildPods;
function getDeploymentConfig() {
return __awaiter(this, void 0, void 0, function* () {
let helmChartPaths = (process.env.HELM_CHART_PATHS && process.env.HELM_CHART_PATHS.split(';').filter(path => path != "")) || [];
helmChartPaths = helmChartPaths.map(helmchart => getNormalizedPath(helmchart.trim()));
let inputManifestFiles = inputParams.manifests || [];
if (!helmChartPaths.length) {
inputManifestFiles = inputManifestFiles.map(manifestFile => getNormalizedPath(manifestFile));
}
const imageNames = inputParams.containers || [];
let imageDockerfilePathMap = {};
//Fetching from image label if available
for (const image of imageNames) {
try {
imageDockerfilePathMap[image] = yield getDockerfilePath(image);
}
catch (ex) {
core.warning(`Failed to get dockerfile path for image ${image.toString()} | ` + ex);
}
}
const deploymentConfig = {
manifestFilePaths: inputManifestFiles,
helmChartFilePaths: helmChartPaths,
dockerfilePaths: imageDockerfilePathMap
};
return Promise.resolve(deploymentConfig);
});
}
exports.getDeploymentConfig = getDeploymentConfig;
function sleep(timeout) {
return new Promise(resolve => setTimeout(resolve, timeout));
}
exports.sleep = sleep;
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
exports.getRandomInt = getRandomInt;
function getCurrentTime() {
return new Date().getTime();
}
exports.getCurrentTime = getCurrentTime;
function checkDockerPath() {
return __awaiter(this, void 0, void 0, function* () {
let dockerPath = yield io.which('docker', false);
if (!dockerPath) {
throw new Error('Docker is not installed.');
}
});
}
function getDockerfilePath(image) {
return __awaiter(this, void 0, void 0, function* () {
let imageConfig, imageInspectResult;
var dockerExec = new docker_object_model_1.DockerExec('docker');
yield checkDockerPath();
dockerExec.pull(image, [], true);
imageInspectResult = dockerExec.inspect(image, [], true);
imageConfig = JSON.parse(imageInspectResult)[0];
const DOCKERFILE_PATH_LABEL_KEY = 'dockerfile-path';
let pathValue = '';
if (imageConfig) {
if ((imageConfig.Config) && (imageConfig.Config.Labels) && (imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY])) {
const pathLabel = imageConfig.Config.Labels[DOCKERFILE_PATH_LABEL_KEY];
pathValue = getNormalizedPath(pathLabel);
}
}
return pathValue;
});
}
function isHttpUrl(url) {
const HTTP_REGEX = /^https?:\/\/.*$/;
return HTTP_REGEX.test(url);
}
exports.isHttpUrl = isHttpUrl;
function getNormalizedPath(pathValue) {
if (!isHttpUrl(pathValue)) { //if it is not an http url then convert to link from current repo and commit
return `https://github.com/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${pathValue}`;
}
return pathValue;
}
exports.getNormalizedPath = getNormalizedPath;
Generated Vendored
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../esprima/bin/esparse.js" "$@"
ret=$?
else
node "$basedir/../esprima/bin/esparse.js" "$@"
ret=$?
fi
exit $ret
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../esprima/bin/esparse.js
-7
View File
@@ -1,7 +0,0 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\esprima\bin\esparse.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\esprima\bin\esparse.js" %*
)
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../esprima/bin/esvalidate.js" "$@"
ret=$?
else
node "$basedir/../esprima/bin/esvalidate.js" "$@"
ret=$?
fi
exit $ret
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../esprima/bin/esvalidate.js
-7
View File
@@ -1,7 +0,0 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\esprima\bin\esvalidate.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\esprima\bin\esvalidate.js" %*
)
Generated Vendored
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@"
ret=$?
else
node "$basedir/../js-yaml/bin/js-yaml.js" "$@"
ret=$?
fi
exit $ret
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js
-7
View File
@@ -1,7 +0,0 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\js-yaml\bin\js-yaml.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\js-yaml\bin\js-yaml.js" %*
)
Generated Vendored
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
ret=$?
else
node "$basedir/../semver/bin/semver.js" "$@"
ret=$?
fi
exit $ret
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../semver/bin/semver.js
-7
View File
@@ -1,7 +0,0 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\semver\bin\semver.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\semver\bin\semver.js" %*
)
Generated Vendored
-15
View File
@@ -1,15 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../uuid/bin/uuid" "$@"
ret=$?
else
node "$basedir/../uuid/bin/uuid" "$@"
ret=$?
fi
exit $ret
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../uuid/bin/uuid
Generated Vendored
-7
View File
@@ -1,7 +0,0 @@
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\uuid\bin\uuid" %*
)
+5
View File
@@ -13,4 +13,9 @@ interface CommandProperties {
*/ */
export declare function issueCommand(command: string, properties: CommandProperties, message: any): void; export declare function issueCommand(command: string, properties: CommandProperties, message: any): void;
export declare function issue(name: string, message?: string): void; export declare function issue(name: string, message?: string): void;
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
export declare function toCommandValue(input: any): string;
export {}; export {};
+16 -3
View File
@@ -8,7 +8,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const os = __importStar(require("os")); const os = __importStar(require("os"));
const utils_1 = require("./utils");
/** /**
* Commands * Commands
* *
@@ -62,14 +61,28 @@ class Command {
return cmdStr; return cmdStr;
} }
} }
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
function toCommandValue(input) {
if (input === null || input === undefined) {
return '';
}
else if (typeof input === 'string' || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
function escapeData(s) { function escapeData(s) {
return utils_1.toCommandValue(s) return toCommandValue(s)
.replace(/%/g, '%25') .replace(/%/g, '%25')
.replace(/\r/g, '%0D') .replace(/\r/g, '%0D')
.replace(/\n/g, '%0A'); .replace(/\n/g, '%0A');
} }
function escapeProperty(s) { function escapeProperty(s) {
return utils_1.toCommandValue(s) return toCommandValue(s)
.replace(/%/g, '%25') .replace(/%/g, '%25')
.replace(/\r/g, '%0D') .replace(/\r/g, '%0D')
.replace(/\n/g, '%0A') .replace(/\n/g, '%0A')
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAwB;AACxB,mCAAsC;AAWtC;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAY;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAM;IACxB,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAM;IAC5B,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"} {"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAwB;AAWxB;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAY;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED;;;GAGG;AACH,SAAgB,cAAc,CAAC,KAAU;IACvC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;QACzC,OAAO,EAAE,CAAA;KACV;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,MAAM,EAAE;QAC/D,OAAO,KAAe,CAAA;KACvB;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAPD,wCAOC;AAED,SAAS,UAAU,CAAC,CAAM;IACxB,OAAO,cAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAM;IAC5B,OAAO,cAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}
+3 -19
View File
@@ -17,8 +17,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = require("./command"); const command_1 = require("./command");
const file_command_1 = require("./file-command");
const utils_1 = require("./utils");
const os = __importStar(require("os")); const os = __importStar(require("os"));
const path = __importStar(require("path")); const path = __importStar(require("path"));
/** /**
@@ -45,17 +43,9 @@ var ExitCode;
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
function exportVariable(name, val) { function exportVariable(name, val) {
const convertedVal = utils_1.toCommandValue(val); const convertedVal = command_1.toCommandValue(val);
process.env[name] = convertedVal; process.env[name] = convertedVal;
const filePath = process.env['GITHUB_ENV'] || ''; command_1.issueCommand('set-env', { name }, convertedVal);
if (filePath) {
const delimiter = '_GitHubActionsFileCommandDelimeter_';
const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;
file_command_1.issueCommand('ENV', commandValue);
}
else {
command_1.issueCommand('set-env', { name }, convertedVal);
}
} }
exports.exportVariable = exportVariable; exports.exportVariable = exportVariable;
/** /**
@@ -71,13 +61,7 @@ exports.setSecret = setSecret;
* @param inputPath * @param inputPath
*/ */
function addPath(inputPath) { function addPath(inputPath) {
const filePath = process.env['GITHUB_PATH'] || ''; command_1.issueCommand('add-path', {}, inputPath);
if (filePath) {
file_command_1.issueCommand('PATH', inputPath);
}
else {
command_1.issueCommand('add-path', {}, inputPath);
}
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
} }
exports.addPath = addPath; exports.addPath = addPath;
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,uCAA6C;AAC7C,iDAA+D;AAC/D,mCAAsC;AAEtC,uCAAwB;AACxB,2CAA4B;AAU5B;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAED,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,8DAA8D;AAC9D,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAQ;IACnD,MAAM,YAAY,GAAG,sBAAc,CAAC,GAAG,CAAC,CAAA;IACxC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAA;IAEhC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,CAAA;IAChD,IAAI,QAAQ,EAAE;QACZ,MAAM,SAAS,GAAG,qCAAqC,CAAA;QACvD,MAAM,YAAY,GAAG,GAAG,IAAI,KAAK,SAAS,GAAG,EAAE,CAAC,GAAG,GAAG,YAAY,GAAG,EAAE,CAAC,GAAG,GAAG,SAAS,EAAE,CAAA;QACzF,2BAAgB,CAAC,KAAK,EAAE,YAAY,CAAC,CAAA;KACtC;SAAM;QACL,sBAAY,CAAC,SAAS,EAAE,EAAC,IAAI,EAAC,EAAE,YAAY,CAAC,CAAA;KAC9C;AACH,CAAC;AAZD,wCAYC;AAED;;;GAGG;AACH,SAAgB,SAAS,CAAC,MAAc;IACtC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAFD,8BAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,SAAiB;IACvC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,CAAA;IACjD,IAAI,QAAQ,EAAE;QACZ,2BAAgB,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;KACpC;SAAM;QACL,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,SAAS,CAAC,CAAA;KACxC;IACD,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;AAC7E,CAAC;AARD,0BAQC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,IAAY,EAAE,OAAsB;IAC3D,MAAM,GAAG,GACP,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,EAAE,CAAA;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAA;KAC5D;IAED,OAAO,GAAG,CAAC,IAAI,EAAE,CAAA;AACnB,CAAC;AARD,4BAQC;AAED;;;;;GAKG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAU;IAChD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;GAIG;AACH,SAAgB,cAAc,CAAC,OAAgB;IAC7C,eAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAA;AACvC,CAAC;AAFD,wCAEC;AAED,yEAAyE;AACzE,UAAU;AACV,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,SAAS,CAAC,OAAuB;IAC/C,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAA;IAEnC,KAAK,CAAC,OAAO,CAAC,CAAA;AAChB,CAAC;AAJD,8BAIC;AAED,yEAAyE;AACzE,mBAAmB;AACnB,yEAAyE;AAEzE;;GAEG;AACH,SAAgB,OAAO;IACrB,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,KAAK,GAAG,CAAA;AAC5C,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,sBAAY,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAuB;IAC3C,eAAK,CAAC,OAAO,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;AACzE,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,OAAuB;IAC7C,eAAK,CAAC,SAAS,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;AAC3E,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,IAAI,CAAC,OAAe;IAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,oBAEC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,eAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,QAAQ;IACtB,eAAK,CAAC,UAAU,CAAC,CAAA;AACnB,CAAC;AAFD,4BAEC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAI,IAAY,EAAE,EAAoB;;QAC/D,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhB,IAAI,MAAS,CAAA;QAEb,IAAI;YACF,MAAM,GAAG,MAAM,EAAE,EAAE,CAAA;SACpB;gBAAS;YACR,QAAQ,EAAE,CAAA;SACX;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAZD,sBAYC;AAED,yEAAyE;AACzE,uBAAuB;AACvB,yEAAyE;AAEzE;;;;;GAKG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAU;IAChD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;AAC3C,CAAC;AAFD,4BAEC"} {"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,uCAA6D;AAE7D,uCAAwB;AACxB,2CAA4B;AAU5B;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAED,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,8DAA8D;AAC9D,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAQ;IACnD,MAAM,YAAY,GAAG,wBAAc,CAAC,GAAG,CAAC,CAAA;IACxC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAA;IAChC,sBAAY,CAAC,SAAS,EAAE,EAAC,IAAI,EAAC,EAAE,YAAY,CAAC,CAAA;AAC/C,CAAC;AAJD,wCAIC;AAED;;;GAGG;AACH,SAAgB,SAAS,CAAC,MAAc;IACtC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,MAAM,CAAC,CAAA;AACtC,CAAC;AAFD,8BAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,SAAiB;IACvC,sBAAY,CAAC,UAAU,EAAE,EAAE,EAAE,SAAS,CAAC,CAAA;IACvC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;AAC7E,CAAC;AAHD,0BAGC;AAED;;;;;;GAMG;AACH,SAAgB,QAAQ,CAAC,IAAY,EAAE,OAAsB;IAC3D,MAAM,GAAG,GACP,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,EAAE,CAAA;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE;QACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,IAAI,EAAE,CAAC,CAAA;KAC5D;IAED,OAAO,GAAG,CAAC,IAAI,EAAE,CAAA;AACnB,CAAC;AARD,4BAQC;AAED;;;;;GAKG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAU;IAChD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;GAIG;AACH,SAAgB,cAAc,CAAC,OAAgB;IAC7C,eAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAA;AACvC,CAAC;AAFD,wCAEC;AAED,yEAAyE;AACzE,UAAU;AACV,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,SAAS,CAAC,OAAuB;IAC/C,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAA;IAEnC,KAAK,CAAC,OAAO,CAAC,CAAA;AAChB,CAAC;AAJD,8BAIC;AAED,yEAAyE;AACzE,mBAAmB;AACnB,yEAAyE;AAEzE;;GAEG;AACH,SAAgB,OAAO;IACrB,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,KAAK,GAAG,CAAA;AAC5C,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAe;IACnC,sBAAY,CAAC,OAAO,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACpC,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,KAAK,CAAC,OAAuB;IAC3C,eAAK,CAAC,OAAO,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;AACzE,CAAC;AAFD,sBAEC;AAED;;;GAGG;AACH,SAAgB,OAAO,CAAC,OAAuB;IAC7C,eAAK,CAAC,SAAS,EAAE,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;AAC3E,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,IAAI,CAAC,OAAe;IAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,oBAEC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,eAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,QAAQ;IACtB,eAAK,CAAC,UAAU,CAAC,CAAA;AACnB,CAAC;AAFD,4BAEC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAI,IAAY,EAAE,EAAoB;;QAC/D,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhB,IAAI,MAAS,CAAA;QAEb,IAAI;YACF,MAAM,GAAG,MAAM,EAAE,EAAE,CAAA;SACpB;gBAAS;YACR,QAAQ,EAAE,CAAA;SACX;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAZD,sBAYC;AAED,yEAAyE;AACzE,uBAAuB;AACvB,yEAAyE;AAEzE;;;;;GAKG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAU;IAChD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;AAC3C,CAAC;AAFD,4BAEC"}
-1
View File
@@ -1 +0,0 @@
export declare function issueCommand(command: string, message: any): void;
-29
View File
@@ -1,29 +0,0 @@
"use strict";
// For internal use, subject to change.
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const utils_1 = require("./utils");
function issueCommand(command, message) {
const filePath = process.env[`GITHUB_${command}`];
if (!filePath) {
throw new Error(`Unable to find environment variable for file command ${command}`);
}
if (!fs.existsSync(filePath)) {
throw new Error(`Missing file at path: ${filePath}`);
}
fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {
encoding: 'utf8'
});
}
exports.issueCommand = issueCommand;
//# sourceMappingURL=file-command.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"file-command.js","sourceRoot":"","sources":["../src/file-command.ts"],"names":[],"mappings":";AAAA,uCAAuC;;;;;;;;;AAEvC,mCAAmC;AACnC,uDAAuD;AAEvD,uCAAwB;AACxB,uCAAwB;AACxB,mCAAsC;AAEtC,SAAgB,YAAY,CAAC,OAAe,EAAE,OAAY;IACxD,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,EAAE,CAAC,CAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CACb,wDAAwD,OAAO,EAAE,CAClE,CAAA;KACF;IACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,EAAE,CAAC,CAAA;KACrD;IAED,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,sBAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACjE,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;AACJ,CAAC;AAdD,oCAcC"}
-5
View File
@@ -1,5 +0,0 @@
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
export declare function toCommandValue(input: any): string;
-19
View File
@@ -1,19 +0,0 @@
"use strict";
// We use any as a valid input type
/* eslint-disable @typescript-eslint/no-explicit-any */
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Sanitizes an input into a string so it can be passed into issueCommand safely
* @param input input to sanitize into a string
*/
function toCommandValue(input) {
if (input === null || input === undefined) {
return '';
}
else if (typeof input === 'string' || input instanceof String) {
return input;
}
return JSON.stringify(input);
}
exports.toCommandValue = toCommandValue;
//# sourceMappingURL=utils.js.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA,mCAAmC;AACnC,uDAAuD;;AAEvD;;;GAGG;AACH,SAAgB,cAAc,CAAC,KAAU;IACvC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;QACzC,OAAO,EAAE,CAAA;KACV;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,MAAM,EAAE;QAC/D,OAAO,KAAe,CAAA;KACvB;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAPD,wCAOC"}
+12 -12
View File
@@ -1,29 +1,29 @@
{ {
"_from": "@actions/core@^1.2.6", "_from": "@actions/core@1.2.5",
"_id": "@actions/core@1.2.6", "_id": "@actions/core@1.2.5",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-ZQYitnqiyBc3D+k7LsgSBmMDVkOVidaagDG7j3fOym77jNunWRuYx7VSHa9GNfFZh+zh61xsCjRj4JxMZlDqTA==", "_integrity": "sha512-mwpoNjHSWWh0IiALdDEQi3tru124JKn0yVNziIBzTME8QRv7thwoghVuT1jBRjFvdtoHsqD58IRHy1nf86paRg==",
"_location": "/@actions/core", "_location": "/@actions/core",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "range", "type": "version",
"registry": true, "registry": true,
"raw": "@actions/core@^1.2.6", "raw": "@actions/core@1.2.5",
"name": "@actions/core", "name": "@actions/core",
"escapedName": "@actions%2fcore", "escapedName": "@actions%2fcore",
"scope": "@actions", "scope": "@actions",
"rawSpec": "^1.2.6", "rawSpec": "1.2.5",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "^1.2.6" "fetchSpec": "1.2.5"
}, },
"_requiredBy": [ "_requiredBy": [
"/", "/",
"/@actions/tool-cache" "/@actions/tool-cache"
], ],
"_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.6.tgz", "_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.5.tgz",
"_shasum": "a78d49f41a4def18e88ce47c2cac615d5694bf09", "_shasum": "fa57bf8c07a38191e243beb9ea9d8368c1cb02c8",
"_spec": "@actions/core@^1.2.6", "_spec": "@actions/core@1.2.5",
"_where": "C:\\Users\\kodey\\workspace\\github-actions\\k8s-deploy", "_where": "/Users/aj/repos/k8s-deploy",
"bugs": { "bugs": {
"url": "https://github.com/actions/toolkit/issues" "url": "https://github.com/actions/toolkit/issues"
}, },
@@ -64,5 +64,5 @@
"tsc": "tsc" "tsc": "tsc"
}, },
"types": "lib/core.d.ts", "types": "lib/core.d.ts",
"version": "1.2.6" "version": "1.2.5"
} }
-7
View File
@@ -1,7 +0,0 @@
Copyright 2019 GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+3 -6
View File
@@ -4,7 +4,7 @@
#### Basic #### Basic
You can use this package to execute your tools on the command line in a cross platform way: You can use this package to execute tools in a cross platform way:
```js ```js
const exec = require('@actions/exec'); const exec = require('@actions/exec');
@@ -48,13 +48,10 @@ await exec.exec('node', ['index.js', 'foo=bar'], options);
#### Exec tools not in the PATH #### Exec tools not in the PATH
You can use it in conjunction with the `which` function from `@actions/io` to execute tools that are not in the PATH: You can specify the full path for tools not in the PATH:
```js ```js
const exec = require('@actions/exec'); const exec = require('@actions/exec');
const io = require('@actions/io');
const pythonPath: string = await io.which('python', true) await exec.exec('"/path/to/my-tool"', ['arg1']);
await exec.exec(`"${pythonPath}"`, ['main.py']);
``` ```
+3 -2
View File
@@ -1,4 +1,5 @@
import * as im from './interfaces'; import { ExecOptions } from './interfaces';
export { ExecOptions };
/** /**
* Exec a command. * Exec a command.
* Output will be streamed to the live console. * Output will be streamed to the live console.
@@ -9,4 +10,4 @@ import * as im from './interfaces';
* @param options optional exec options. See ExecOptions * @param options optional exec options. See ExecOptions
* @returns Promise<number> exit code * @returns Promise<number> exit code
*/ */
export declare function exec(commandLine: string, args?: string[], options?: im.ExecOptions): Promise<number>; export declare function exec(commandLine: string, args?: string[], options?: ExecOptions): Promise<number>;
+8 -1
View File
@@ -8,8 +8,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const tr = require("./toolrunner"); const tr = __importStar(require("./toolrunner"));
/** /**
* Exec a command. * Exec a command.
* Output will be streamed to the live console. * Output will be streamed to the live console.
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,mCAAkC;AAElC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAwB;;QAExB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC"} {"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,iDAAkC;AAIlC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAqB;;QAErB,MAAM,WAAW,GAAG,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAA;QACpD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAA;SACpE;QACD,8CAA8C;QAC9C,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,CAAA;QAC/B,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC,CAAA;QAC9C,MAAM,MAAM,GAAkB,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAA;QACxE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAA;IACtB,CAAC;CAAA;AAdD,oBAcC"}
+2
View File
@@ -24,6 +24,8 @@ export interface ExecOptions {
ignoreReturnCode?: boolean; ignoreReturnCode?: boolean;
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */ /** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
delay?: number; delay?: number;
/** optional. input to write to the process on STDIN. */
input?: Buffer;
/** optional. Listeners for output. Callback functions that will be called on these events */ /** optional. Listeners for output. Callback functions that will be called on these events */
listeners?: { listeners?: {
stdout?: (data: Buffer) => void; stdout?: (data: Buffer) => void;
+29 -3
View File
@@ -8,10 +8,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os"); const os = __importStar(require("os"));
const events = require("events"); const events = __importStar(require("events"));
const child = require("child_process"); const child = __importStar(require("child_process"));
const path = __importStar(require("path"));
const io = __importStar(require("@actions/io"));
const ioUtil = __importStar(require("@actions/io/lib/io-util"));
/* eslint-disable @typescript-eslint/unbound-method */ /* eslint-disable @typescript-eslint/unbound-method */
const IS_WINDOWS = process.platform === 'win32'; const IS_WINDOWS = process.platform === 'win32';
/* /*
@@ -357,6 +367,16 @@ class ToolRunner extends events.EventEmitter {
*/ */
exec() { exec() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// root the tool path if it is unrooted and contains relative pathing
if (!ioUtil.isRooted(this.toolPath) &&
(this.toolPath.includes('/') ||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
}
// if the tool is only a file name, then resolve it from the PATH
// otherwise verify it exists (add extension on Windows if necessary)
this.toolPath = yield io.which(this.toolPath, true);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._debug(`exec tool: ${this.toolPath}`); this._debug(`exec tool: ${this.toolPath}`);
this._debug('arguments:'); this._debug('arguments:');
@@ -445,6 +465,12 @@ class ToolRunner extends events.EventEmitter {
resolve(exitCode); resolve(exitCode);
} }
}); });
if (this.options.input) {
if (!cp.stdin) {
throw new Error('child process missing stdin');
}
cp.stdin.end(this.options.input);
}
}); });
}); });
} }
+1 -1
View File
File diff suppressed because one or more lines are too long
+19 -20
View File
@@ -1,41 +1,38 @@
{ {
"_args": [ "_from": "@actions/exec@1.0.4",
[ "_id": "@actions/exec@1.0.4",
"@actions/exec@1.0.1",
"E:\\k8s-actions\\deploy\\k8s-deploy"
]
],
"_from": "@actions/exec@1.0.1",
"_id": "@actions/exec@1.0.1",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-nvFkxwiicvpzNiCBF4wFBDfnBvi7xp/as7LE1hBxBxKG2L29+gkIPBiLKMVORL+Hg3JNf07AKRfl0V5djoypjQ==", "_integrity": "sha512-4DPChWow9yc9W3WqEbUj8Nr86xkpyE29ZzWjXucHItclLbEW6jr80Zx4nqv18QL6KK65+cifiQZXvnqgTV6oHw==",
"_location": "/@actions/exec", "_location": "/@actions/exec",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@actions/exec@1.0.1", "raw": "@actions/exec@1.0.4",
"name": "@actions/exec", "name": "@actions/exec",
"escapedName": "@actions%2fexec", "escapedName": "@actions%2fexec",
"scope": "@actions", "scope": "@actions",
"rawSpec": "1.0.1", "rawSpec": "1.0.4",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "1.0.1" "fetchSpec": "1.0.4"
}, },
"_requiredBy": [ "_requiredBy": [
"/", "/",
"/@actions/tool-cache" "/@actions/tool-cache"
], ],
"_resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.1.tgz", "_resolved": "https://registry.npmjs.org/@actions/exec/-/exec-1.0.4.tgz",
"_spec": "1.0.1", "_shasum": "99d75310e62e59fc37d2ee6dcff6d4bffadd3a5d",
"_where": "E:\\k8s-actions\\deploy\\k8s-deploy", "_spec": "@actions/exec@1.0.4",
"_where": "/Users/aj/repos/k8s-deploy",
"bugs": { "bugs": {
"url": "https://github.com/actions/toolkit/issues" "url": "https://github.com/actions/toolkit/issues"
}, },
"description": "Actions exec lib", "bundleDependencies": false,
"devDependencies": { "dependencies": {
"@actions/io": "^1.0.1" "@actions/io": "^1.0.1"
}, },
"deprecated": false,
"description": "Actions exec lib",
"directories": { "directories": {
"lib": "lib", "lib": "lib",
"test": "__tests__" "test": "__tests__"
@@ -43,7 +40,6 @@
"files": [ "files": [
"lib" "lib"
], ],
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52",
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec", "homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
"keywords": [ "keywords": [
"github", "github",
@@ -58,11 +54,14 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/actions/toolkit.git" "url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/exec"
}, },
"scripts": { "scripts": {
"audit-moderate": "npm install && npm audit --audit-level=moderate",
"test": "echo \"Error: run tests from root\" && exit 1", "test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc" "tsc": "tsc"
}, },
"version": "1.0.1" "types": "lib/exec.d.ts",
"version": "1.0.4"
} }
+21
View File
@@ -0,0 +1,21 @@
Actions Http Client for Node.js
Copyright (c) GitHub, Inc.
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+79
View File
@@ -0,0 +1,79 @@
<p align="center">
<img src="actions.png">
</p>
# Actions Http-Client
[![Http Status](https://github.com/actions/http-client/workflows/http-tests/badge.svg)](https://github.com/actions/http-client/actions)
A lightweight HTTP client optimized for use with actions, TypeScript with generics and async await.
## Features
- HTTP client with TypeScript generics and async/await/Promises
- Typings included so no need to acquire separately (great for intellisense and no versioning drift)
- [Proxy support](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/about-self-hosted-runners#using-a-proxy-server-with-self-hosted-runners) just works with actions and the runner
- Targets ES2019 (runner runs actions with node 12+). Only supported on node 12+.
- Basic, Bearer and PAT Support out of the box. Extensible handlers for others.
- Redirects supported
Features and releases [here](./RELEASES.md)
## Install
```
npm install @actions/http-client --save
```
## Samples
See the [HTTP](./__tests__) tests for detailed examples.
## Errors
### HTTP
The HTTP client does not throw unless truly exceptional.
* A request that successfully executes resulting in a 404, 500 etc... will return a response object with a status code and a body.
* Redirects (3xx) will be followed by default.
See [HTTP tests](./__tests__) for detailed examples.
## Debugging
To enable detailed console logging of all HTTP requests and responses, set the NODE_DEBUG environment varible:
```
export NODE_DEBUG=http
```
## Node support
The http-client is built using the latest LTS version of Node 12. It may work on previous node LTS versions but it's tested and officially supported on Node12+.
## Support and Versioning
We follow semver and will hold compatibility between major versions and increment the minor version with new features and capabilities (while holding compat).
## Contributing
We welcome PRs. Please create an issue and if applicable, a design before proceeding with code.
once:
```bash
$ npm install
```
To build:
```bash
$ npm run build
```
To run all tests:
```bash
$ npm test
```
+16
View File
@@ -0,0 +1,16 @@
## Releases
## 1.0.7
Update NPM dependencies and add 429 to the list of HttpCodes
## 1.0.6
Automatically sends Content-Type and Accept application/json headers for \<verb>Json() helper methods if not set in the client or parameters.
## 1.0.5
Adds \<verb>Json() helper methods for json over http scenarios.
## 1.0.4
Started to add \<verb>Json() helper methods. Do not use this release for that. Use >= 1.0.5 since there was an issue with types.
## 1.0.1 to 1.0.3
Adds proxy support.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+23
View File
@@ -0,0 +1,23 @@
import ifm = require('./interfaces');
export declare class BasicCredentialHandler implements ifm.IRequestHandler {
username: string;
password: string;
constructor(username: string, password: string);
prepareRequest(options: any): void;
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
}
export declare class BearerCredentialHandler implements ifm.IRequestHandler {
token: string;
constructor(token: string);
prepareRequest(options: any): void;
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
}
export declare class PersonalAccessTokenCredentialHandler implements ifm.IRequestHandler {
token: string;
constructor(token: string);
prepareRequest(options: any): void;
canHandleAuthentication(response: ifm.IHttpClientResponse): boolean;
handleAuthentication(httpClient: ifm.IHttpClient, requestInfo: ifm.IRequestInfo, objs: any): Promise<ifm.IHttpClientResponse>;
}
+58
View File
@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class BasicCredentialHandler {
constructor(username, password) {
this.username = username;
this.password = password;
}
prepareRequest(options) {
options.headers['Authorization'] =
'Basic ' +
Buffer.from(this.username + ':' + this.password).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.BasicCredentialHandler = BasicCredentialHandler;
class BearerCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
options.headers['Authorization'] = 'Bearer ' + this.token;
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.BearerCredentialHandler = BearerCredentialHandler;
class PersonalAccessTokenCredentialHandler {
constructor(token) {
this.token = token;
}
// currently implements pre-authorization
// TODO: support preAuth = false where it hooks on 401
prepareRequest(options) {
options.headers['Authorization'] =
'Basic ' + Buffer.from('PAT:' + this.token).toString('base64');
}
// This handler cannot handle 401
canHandleAuthentication(response) {
return false;
}
handleAuthentication(httpClient, requestInfo, objs) {
return null;
}
}
exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler;
+119
View File
@@ -0,0 +1,119 @@
/// <reference types="node" />
import http = require('http');
import ifm = require('./interfaces');
export declare enum HttpCodes {
OK = 200,
MultipleChoices = 300,
MovedPermanently = 301,
ResourceMoved = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
SwitchProxy = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
TooManyRequests = 429,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504
}
export declare enum Headers {
Accept = "accept",
ContentType = "content-type"
}
export declare enum MediaTypes {
ApplicationJson = "application/json"
}
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
export declare function getProxyUrl(serverUrl: string): string;
export declare class HttpClientResponse implements ifm.IHttpClientResponse {
constructor(message: http.IncomingMessage);
message: http.IncomingMessage;
readBody(): Promise<string>;
}
export declare function isHttps(requestUrl: string): boolean;
export declare class HttpClient {
userAgent: string | undefined;
handlers: ifm.IRequestHandler[];
requestOptions: ifm.IRequestOptions;
private _ignoreSslError;
private _socketTimeout;
private _allowRedirects;
private _allowRedirectDowngrade;
private _maxRedirects;
private _allowRetries;
private _maxRetries;
private _agent;
private _proxyAgent;
private _keepAlive;
private _disposed;
constructor(userAgent?: string, handlers?: ifm.IRequestHandler[], requestOptions?: ifm.IRequestOptions);
options(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
get(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
del(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
post(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
patch(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
put(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
head(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
/**
* Gets a typed object from an endpoint
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
getJson<T>(requestUrl: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
postJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
putJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
patchJson<T>(requestUrl: string, obj: any, additionalHeaders?: ifm.IHeaders): Promise<ifm.ITypedResponse<T>>;
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
/**
* Needs to be called if keepAlive is set to true in request options.
*/
dispose(): void;
/**
* Raw request.
* @param info
* @param data
*/
requestRaw(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream): Promise<ifm.IHttpClientResponse>;
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: ifm.IHttpClientResponse) => void): void;
/**
* Gets an http agent. This function is useful when you need an http agent that handles
* routing through a proxy server - depending upon the url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
getAgent(serverUrl: string): http.Agent;
private _prepareRequest;
private _mergeHeaders;
private _getExistingOrDefaultHeader;
private _getAgent;
private _performExponentialBackoff;
private static dateTimeDeserializer;
private _processResponse;
}
+531
View File
@@ -0,0 +1,531 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url = require("url");
const http = require("http");
const https = require("https");
const pm = require("./proxy");
let tunnel;
var HttpCodes;
(function (HttpCodes) {
HttpCodes[HttpCodes["OK"] = 200] = "OK";
HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices";
HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently";
HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved";
HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther";
HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified";
HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy";
HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy";
HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect";
HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect";
HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest";
HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized";
HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired";
HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden";
HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound";
HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed";
HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable";
HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout";
HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict";
HttpCodes[HttpCodes["Gone"] = 410] = "Gone";
HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests";
HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError";
HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented";
HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway";
HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable";
HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout";
})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {}));
var Headers;
(function (Headers) {
Headers["Accept"] = "accept";
Headers["ContentType"] = "content-type";
})(Headers = exports.Headers || (exports.Headers = {}));
var MediaTypes;
(function (MediaTypes) {
MediaTypes["ApplicationJson"] = "application/json";
})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {}));
/**
* Returns the proxy URL, depending upon the supplied url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
function getProxyUrl(serverUrl) {
let proxyUrl = pm.getProxyUrl(url.parse(serverUrl));
return proxyUrl ? proxyUrl.href : '';
}
exports.getProxyUrl = getProxyUrl;
const HttpRedirectCodes = [
HttpCodes.MovedPermanently,
HttpCodes.ResourceMoved,
HttpCodes.SeeOther,
HttpCodes.TemporaryRedirect,
HttpCodes.PermanentRedirect
];
const HttpResponseRetryCodes = [
HttpCodes.BadGateway,
HttpCodes.ServiceUnavailable,
HttpCodes.GatewayTimeout
];
const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD'];
const ExponentialBackoffCeiling = 10;
const ExponentialBackoffTimeSlice = 5;
class HttpClientResponse {
constructor(message) {
this.message = message;
}
readBody() {
return new Promise(async (resolve, reject) => {
let output = Buffer.alloc(0);
this.message.on('data', (chunk) => {
output = Buffer.concat([output, chunk]);
});
this.message.on('end', () => {
resolve(output.toString());
});
});
}
}
exports.HttpClientResponse = HttpClientResponse;
function isHttps(requestUrl) {
let parsedUrl = url.parse(requestUrl);
return parsedUrl.protocol === 'https:';
}
exports.isHttps = isHttps;
class HttpClient {
constructor(userAgent, handlers, requestOptions) {
this._ignoreSslError = false;
this._allowRedirects = true;
this._allowRedirectDowngrade = false;
this._maxRedirects = 50;
this._allowRetries = false;
this._maxRetries = 1;
this._keepAlive = false;
this._disposed = false;
this.userAgent = userAgent;
this.handlers = handlers || [];
this.requestOptions = requestOptions;
if (requestOptions) {
if (requestOptions.ignoreSslError != null) {
this._ignoreSslError = requestOptions.ignoreSslError;
}
this._socketTimeout = requestOptions.socketTimeout;
if (requestOptions.allowRedirects != null) {
this._allowRedirects = requestOptions.allowRedirects;
}
if (requestOptions.allowRedirectDowngrade != null) {
this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade;
}
if (requestOptions.maxRedirects != null) {
this._maxRedirects = Math.max(requestOptions.maxRedirects, 0);
}
if (requestOptions.keepAlive != null) {
this._keepAlive = requestOptions.keepAlive;
}
if (requestOptions.allowRetries != null) {
this._allowRetries = requestOptions.allowRetries;
}
if (requestOptions.maxRetries != null) {
this._maxRetries = requestOptions.maxRetries;
}
}
}
options(requestUrl, additionalHeaders) {
return this.request('OPTIONS', requestUrl, null, additionalHeaders || {});
}
get(requestUrl, additionalHeaders) {
return this.request('GET', requestUrl, null, additionalHeaders || {});
}
del(requestUrl, additionalHeaders) {
return this.request('DELETE', requestUrl, null, additionalHeaders || {});
}
post(requestUrl, data, additionalHeaders) {
return this.request('POST', requestUrl, data, additionalHeaders || {});
}
patch(requestUrl, data, additionalHeaders) {
return this.request('PATCH', requestUrl, data, additionalHeaders || {});
}
put(requestUrl, data, additionalHeaders) {
return this.request('PUT', requestUrl, data, additionalHeaders || {});
}
head(requestUrl, additionalHeaders) {
return this.request('HEAD', requestUrl, null, additionalHeaders || {});
}
sendStream(verb, requestUrl, stream, additionalHeaders) {
return this.request(verb, requestUrl, stream, additionalHeaders);
}
/**
* Gets a typed object from an endpoint
* Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise
*/
async getJson(requestUrl, additionalHeaders = {}) {
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
let res = await this.get(requestUrl, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async postJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.post(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async putJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.put(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
async patchJson(requestUrl, obj, additionalHeaders = {}) {
let data = JSON.stringify(obj, null, 2);
additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson);
additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson);
let res = await this.patch(requestUrl, data, additionalHeaders);
return this._processResponse(res, this.requestOptions);
}
/**
* Makes a raw http request.
* All other methods such as get, post, patch, and request ultimately call this.
* Prefer get, del, post and patch
*/
async request(verb, requestUrl, data, headers) {
if (this._disposed) {
throw new Error('Client has already been disposed.');
}
let parsedUrl = url.parse(requestUrl);
let info = this._prepareRequest(verb, parsedUrl, headers);
// Only perform retries on reads since writes may not be idempotent.
let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1
? this._maxRetries + 1
: 1;
let numTries = 0;
let response;
while (numTries < maxTries) {
response = await this.requestRaw(info, data);
// Check if it's an authentication challenge
if (response &&
response.message &&
response.message.statusCode === HttpCodes.Unauthorized) {
let authenticationHandler;
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].canHandleAuthentication(response)) {
authenticationHandler = this.handlers[i];
break;
}
}
if (authenticationHandler) {
return authenticationHandler.handleAuthentication(this, info, data);
}
else {
// We have received an unauthorized response but have no handlers to handle it.
// Let the response return to the caller.
return response;
}
}
let redirectsRemaining = this._maxRedirects;
while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 &&
this._allowRedirects &&
redirectsRemaining > 0) {
const redirectUrl = response.message.headers['location'];
if (!redirectUrl) {
// if there's no location to redirect to, we won't
break;
}
let parsedRedirectUrl = url.parse(redirectUrl);
if (parsedUrl.protocol == 'https:' &&
parsedUrl.protocol != parsedRedirectUrl.protocol &&
!this._allowRedirectDowngrade) {
throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.');
}
// we need to finish reading the response before reassigning response
// which will leak the open socket.
await response.readBody();
// strip authorization header if redirected to a different hostname
if (parsedRedirectUrl.hostname !== parsedUrl.hostname) {
for (let header in headers) {
// header names are case insensitive
if (header.toLowerCase() === 'authorization') {
delete headers[header];
}
}
}
// let's make the request with the new redirectUrl
info = this._prepareRequest(verb, parsedRedirectUrl, headers);
response = await this.requestRaw(info, data);
redirectsRemaining--;
}
if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) {
// If not a retry code, return immediately instead of retrying
return response;
}
numTries += 1;
if (numTries < maxTries) {
await response.readBody();
await this._performExponentialBackoff(numTries);
}
}
return response;
}
/**
* Needs to be called if keepAlive is set to true in request options.
*/
dispose() {
if (this._agent) {
this._agent.destroy();
}
this._disposed = true;
}
/**
* Raw request.
* @param info
* @param data
*/
requestRaw(info, data) {
return new Promise((resolve, reject) => {
let callbackForResult = function (err, res) {
if (err) {
reject(err);
}
resolve(res);
};
this.requestRawWithCallback(info, data, callbackForResult);
});
}
/**
* Raw request with callback.
* @param info
* @param data
* @param onResult
*/
requestRawWithCallback(info, data, onResult) {
let socket;
if (typeof data === 'string') {
info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
}
let callbackCalled = false;
let handleResult = (err, res) => {
if (!callbackCalled) {
callbackCalled = true;
onResult(err, res);
}
};
let req = info.httpModule.request(info.options, (msg) => {
let res = new HttpClientResponse(msg);
handleResult(null, res);
});
req.on('socket', sock => {
socket = sock;
});
// If we ever get disconnected, we want the socket to timeout eventually
req.setTimeout(this._socketTimeout || 3 * 60000, () => {
if (socket) {
socket.end();
}
handleResult(new Error('Request timeout: ' + info.options.path), null);
});
req.on('error', function (err) {
// err has statusCode property
// res should have headers
handleResult(err, null);
});
if (data && typeof data === 'string') {
req.write(data, 'utf8');
}
if (data && typeof data !== 'string') {
data.on('close', function () {
req.end();
});
data.pipe(req);
}
else {
req.end();
}
}
/**
* Gets an http agent. This function is useful when you need an http agent that handles
* routing through a proxy server - depending upon the url and proxy environment variables.
* @param serverUrl The server URL where the request will be sent. For example, https://api.github.com
*/
getAgent(serverUrl) {
let parsedUrl = url.parse(serverUrl);
return this._getAgent(parsedUrl);
}
_prepareRequest(method, requestUrl, headers) {
const info = {};
info.parsedUrl = requestUrl;
const usingSsl = info.parsedUrl.protocol === 'https:';
info.httpModule = usingSsl ? https : http;
const defaultPort = usingSsl ? 443 : 80;
info.options = {};
info.options.host = info.parsedUrl.hostname;
info.options.port = info.parsedUrl.port
? parseInt(info.parsedUrl.port)
: defaultPort;
info.options.path =
(info.parsedUrl.pathname || '') + (info.parsedUrl.search || '');
info.options.method = method;
info.options.headers = this._mergeHeaders(headers);
if (this.userAgent != null) {
info.options.headers['user-agent'] = this.userAgent;
}
info.options.agent = this._getAgent(info.parsedUrl);
// gives handlers an opportunity to participate
if (this.handlers) {
this.handlers.forEach(handler => {
handler.prepareRequest(info.options);
});
}
return info;
}
_mergeHeaders(headers) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
if (this.requestOptions && this.requestOptions.headers) {
return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers));
}
return lowercaseKeys(headers || {});
}
_getExistingOrDefaultHeader(additionalHeaders, header, _default) {
const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {});
let clientHeader;
if (this.requestOptions && this.requestOptions.headers) {
clientHeader = lowercaseKeys(this.requestOptions.headers)[header];
}
return additionalHeaders[header] || clientHeader || _default;
}
_getAgent(parsedUrl) {
let agent;
let proxyUrl = pm.getProxyUrl(parsedUrl);
let useProxy = proxyUrl && proxyUrl.hostname;
if (this._keepAlive && useProxy) {
agent = this._proxyAgent;
}
if (this._keepAlive && !useProxy) {
agent = this._agent;
}
// if agent is already assigned use that agent.
if (!!agent) {
return agent;
}
const usingSsl = parsedUrl.protocol === 'https:';
let maxSockets = 100;
if (!!this.requestOptions) {
maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets;
}
if (useProxy) {
// If using proxy, need tunnel
if (!tunnel) {
tunnel = require('tunnel');
}
const agentOptions = {
maxSockets: maxSockets,
keepAlive: this._keepAlive,
proxy: {
proxyAuth: proxyUrl.auth,
host: proxyUrl.hostname,
port: proxyUrl.port
}
};
let tunnelAgent;
const overHttps = proxyUrl.protocol === 'https:';
if (usingSsl) {
tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp;
}
else {
tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp;
}
agent = tunnelAgent(agentOptions);
this._proxyAgent = agent;
}
// if reusing agent across request and tunneling agent isn't assigned create a new agent
if (this._keepAlive && !agent) {
const options = { keepAlive: this._keepAlive, maxSockets: maxSockets };
agent = usingSsl ? new https.Agent(options) : new http.Agent(options);
this._agent = agent;
}
// if not using private agent and tunnel agent isn't setup then use global agent
if (!agent) {
agent = usingSsl ? https.globalAgent : http.globalAgent;
}
if (usingSsl && this._ignoreSslError) {
// we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process
// http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options
// we have to cast it to any and change it directly
agent.options = Object.assign(agent.options || {}, {
rejectUnauthorized: false
});
}
return agent;
}
_performExponentialBackoff(retryNumber) {
retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber);
const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber);
return new Promise(resolve => setTimeout(() => resolve(), ms));
}
static dateTimeDeserializer(key, value) {
if (typeof value === 'string') {
let a = new Date(value);
if (!isNaN(a.valueOf())) {
return a;
}
}
return value;
}
async _processResponse(res, options) {
return new Promise(async (resolve, reject) => {
const statusCode = res.message.statusCode;
const response = {
statusCode: statusCode,
result: null,
headers: {}
};
// not found leads to null obj returned
if (statusCode == HttpCodes.NotFound) {
resolve(response);
}
let obj;
let contents;
// get the result from the body
try {
contents = await res.readBody();
if (contents && contents.length > 0) {
if (options && options.deserializeDates) {
obj = JSON.parse(contents, HttpClient.dateTimeDeserializer);
}
else {
obj = JSON.parse(contents);
}
response.result = obj;
}
response.headers = res.message.headers;
}
catch (err) {
// Invalid resource (contents not json); leaving result obj null
}
// note that 3xx redirects are handled by the http layer.
if (statusCode > 299) {
let msg;
// if exception/error in body, attempt to get better error
if (obj && obj.message) {
msg = obj.message;
}
else if (contents && contents.length > 0) {
// it may be the case that the exception is in the body message as string
msg = contents;
}
else {
msg = 'Failed request: (' + statusCode + ')';
}
let err = new Error(msg);
// attach statusCode and body obj (if available) to the error object
err['statusCode'] = statusCode;
if (response.result) {
err['result'] = response.result;
}
reject(err);
}
else {
resolve(response);
}
});
}
}
exports.HttpClient = HttpClient;
+50
View File
@@ -0,0 +1,50 @@
/// <reference types="node" />
import http = require('http');
import url = require('url');
export interface IHeaders {
[key: string]: any;
}
export interface IHttpClient {
options(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
get(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
del(requestUrl: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
post(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
patch(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
put(requestUrl: string, data: string, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: IHeaders): Promise<IHttpClientResponse>;
request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: IHeaders): Promise<IHttpClientResponse>;
requestRaw(info: IRequestInfo, data: string | NodeJS.ReadableStream): Promise<IHttpClientResponse>;
requestRawWithCallback(info: IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: IHttpClientResponse) => void): void;
}
export interface IRequestHandler {
prepareRequest(options: http.RequestOptions): void;
canHandleAuthentication(response: IHttpClientResponse): boolean;
handleAuthentication(httpClient: IHttpClient, requestInfo: IRequestInfo, objs: any): Promise<IHttpClientResponse>;
}
export interface IHttpClientResponse {
message: http.IncomingMessage;
readBody(): Promise<string>;
}
export interface IRequestInfo {
options: http.RequestOptions;
parsedUrl: url.Url;
httpModule: any;
}
export interface IRequestOptions {
headers?: IHeaders;
socketTimeout?: number;
ignoreSslError?: boolean;
allowRedirects?: boolean;
allowRedirectDowngrade?: boolean;
maxRedirects?: number;
maxSockets?: number;
keepAlive?: boolean;
deserializeDates?: boolean;
allowRetries?: boolean;
maxRetries?: number;
}
export interface ITypedResponse<T> {
statusCode: number;
result: T | null;
headers: Object;
}
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+67
View File
@@ -0,0 +1,67 @@
{
"_from": "@actions/http-client@^1.0.8",
"_id": "@actions/http-client@1.0.8",
"_inBundle": false,
"_integrity": "sha512-G4JjJ6f9Hb3Zvejj+ewLLKLf99ZC+9v+yCxoYf9vSyH+WkzPLB2LuUtRMGNkooMqdugGBFStIKXOuvH1W+EctA==",
"_location": "/@actions/http-client",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@actions/http-client@^1.0.8",
"name": "@actions/http-client",
"escapedName": "@actions%2fhttp-client",
"scope": "@actions",
"rawSpec": "^1.0.8",
"saveSpec": null,
"fetchSpec": "^1.0.8"
},
"_requiredBy": [
"/@actions/tool-cache"
],
"_resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.8.tgz",
"_shasum": "8bd76e8eca89dc8bcf619aa128eba85f7a39af45",
"_spec": "@actions/http-client@^1.0.8",
"_where": "/Users/aj/repos/k8s-deploy/node_modules/@actions/tool-cache",
"author": {
"name": "GitHub, Inc."
},
"bugs": {
"url": "https://github.com/actions/http-client/issues"
},
"bundleDependencies": false,
"dependencies": {
"tunnel": "0.0.6"
},
"deprecated": false,
"description": "Actions Http Client",
"devDependencies": {
"@types/jest": "^25.1.4",
"@types/node": "^12.12.31",
"jest": "^25.1.0",
"prettier": "^2.0.4",
"proxy": "^1.0.1",
"ts-jest": "^25.2.1",
"typescript": "^3.8.3"
},
"homepage": "https://github.com/actions/http-client#readme",
"keywords": [
"Actions",
"Http"
],
"license": "MIT",
"main": "index.js",
"name": "@actions/http-client",
"repository": {
"type": "git",
"url": "git+https://github.com/actions/http-client.git"
},
"scripts": {
"audit-check": "npm audit --audit-level=moderate",
"build": "rm -Rf ./_out && tsc && cp package*.json ./_out && cp *.md ./_out && cp LICENSE ./_out && cp actions.png ./_out",
"format": "prettier --write *.ts && prettier --write **/*.ts",
"format-check": "prettier --check *.ts && prettier --check **/*.ts",
"test": "jest"
},
"version": "1.0.8"
}
+4
View File
@@ -0,0 +1,4 @@
/// <reference types="node" />
import * as url from 'url';
export declare function getProxyUrl(reqUrl: url.Url): url.Url | undefined;
export declare function checkBypass(reqUrl: url.Url): boolean;
+58
View File
@@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url = require("url");
function getProxyUrl(reqUrl) {
let usingSsl = reqUrl.protocol === 'https:';
let proxyUrl;
if (checkBypass(reqUrl)) {
return proxyUrl;
}
let proxyVar;
if (usingSsl) {
proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY'];
}
else {
proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY'];
}
if (proxyVar) {
proxyUrl = url.parse(proxyVar);
}
return proxyUrl;
}
exports.getProxyUrl = getProxyUrl;
function checkBypass(reqUrl) {
if (!reqUrl.hostname) {
return false;
}
let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || '';
if (!noProxy) {
return false;
}
// Determine the request port
let reqPort;
if (reqUrl.port) {
reqPort = Number(reqUrl.port);
}
else if (reqUrl.protocol === 'http:') {
reqPort = 80;
}
else if (reqUrl.protocol === 'https:') {
reqPort = 443;
}
// Format the request hostname and hostname with port
let upperReqHosts = [reqUrl.hostname.toUpperCase()];
if (typeof reqPort === 'number') {
upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`);
}
// Compare request host against noproxy
for (let upperNoProxyItem of noProxy
.split(',')
.map(x => x.trim().toUpperCase())
.filter(x => x)) {
if (upperReqHosts.some(x => x === upperNoProxyItem)) {
return true;
}
}
return false;
}
exports.checkBypass = checkBypass;
-7
View File
@@ -1,7 +0,0 @@
Copyright 2019 GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+18 -18
View File
@@ -1,37 +1,35 @@
{ {
"_args": [ "_from": "@actions/io@1.0.2",
[ "_id": "@actions/io@1.0.2",
"@actions/io@1.0.1",
"E:\\k8s-actions\\deploy\\k8s-deploy"
]
],
"_from": "@actions/io@1.0.1",
"_id": "@actions/io@1.0.1",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-rhq+tfZukbtaus7xyUtwKfuiCRXd1hWSfmJNEpFgBQJ4woqPEpsBw04awicjwz9tyG2/MVhAEMfVn664Cri5zA==", "_integrity": "sha512-J8KuFqVPr3p6U8W93DOXlXW6zFvrQAJANdS+vw0YhusLIq+bszW8zmK2Fh1C2kDPX8FMvwIl1OUcFgvJoXLbAg==",
"_location": "/@actions/io", "_location": "/@actions/io",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@actions/io@1.0.1", "raw": "@actions/io@1.0.2",
"name": "@actions/io", "name": "@actions/io",
"escapedName": "@actions%2fio", "escapedName": "@actions%2fio",
"scope": "@actions", "scope": "@actions",
"rawSpec": "1.0.1", "rawSpec": "1.0.2",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "1.0.1" "fetchSpec": "1.0.2"
}, },
"_requiredBy": [ "_requiredBy": [
"/", "/",
"/@actions/exec",
"/@actions/tool-cache" "/@actions/tool-cache"
], ],
"_resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.1.tgz", "_resolved": "https://registry.npmjs.org/@actions/io/-/io-1.0.2.tgz",
"_spec": "1.0.1", "_shasum": "2f614b6e69ce14d191180451eb38e6576a6e6b27",
"_where": "E:\\k8s-actions\\deploy\\k8s-deploy", "_spec": "@actions/io@1.0.2",
"_where": "/Users/aj/repos/k8s-deploy",
"bugs": { "bugs": {
"url": "https://github.com/actions/toolkit/issues" "url": "https://github.com/actions/toolkit/issues"
}, },
"bundleDependencies": false,
"deprecated": false,
"description": "Actions io lib", "description": "Actions io lib",
"directories": { "directories": {
"lib": "lib", "lib": "lib",
@@ -40,7 +38,6 @@
"files": [ "files": [
"lib" "lib"
], ],
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52",
"homepage": "https://github.com/actions/toolkit/tree/master/packages/io", "homepage": "https://github.com/actions/toolkit/tree/master/packages/io",
"keywords": [ "keywords": [
"github", "github",
@@ -55,11 +52,14 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/actions/toolkit.git" "url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/io"
}, },
"scripts": { "scripts": {
"audit-moderate": "npm install && npm audit --audit-level=moderate",
"test": "echo \"Error: run tests from root\" && exit 1", "test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc" "tsc": "tsc"
}, },
"version": "1.0.1" "types": "lib/io.d.ts",
"version": "1.0.2"
} }
-7
View File
@@ -1,7 +0,0 @@
Copyright 2019 GitHub
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+11 -7
View File
@@ -11,7 +11,7 @@ You can use this to download tools (or other files) from a download URL:
```js ```js
const tc = require('@actions/tool-cache'); const tc = require('@actions/tool-cache');
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz'); const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
``` ```
#### Extract #### Extract
@@ -22,22 +22,26 @@ These can then be extracted in platform specific ways:
const tc = require('@actions/tool-cache'); const tc = require('@actions/tool-cache');
if (process.platform === 'win32') { if (process.platform === 'win32') {
const node12Path = tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip'); const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to'); const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
// Or alternately // Or alternately
const node12Path = tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z'); const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to'); const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
} }
else if (process.platform === 'darwin') {
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0.pkg');
const node12ExtractedFolder = await tc.extractXar(node12Path, 'path/to/extract/to');
}
else { else {
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz'); const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to'); const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
} }
``` ```
#### Cache #### Cache
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for private runners (private runners are still in development but are on the roadmap). Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for self-hosted runners.
You'll often want to add it to the path as part of this step: You'll often want to add it to the path as part of this step:
@@ -45,7 +49,7 @@ You'll often want to add it to the path as part of this step:
const tc = require('@actions/tool-cache'); const tc = require('@actions/tool-cache');
const core = require('@actions/core'); const core = require('@actions/core');
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz'); const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to'); const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0'); const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
@@ -57,7 +61,7 @@ You can also cache files for reuse.
```js ```js
const tc = require('@actions/tool-cache'); const tc = require('@actions/tool-cache');
tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0'); const cachedPath = await tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
``` ```
#### Find #### Find
+16
View File
@@ -0,0 +1,16 @@
export interface IToolReleaseFile {
filename: string;
platform: string;
platform_version?: string;
arch: string;
download_url: string;
}
export interface IToolRelease {
version: string;
stable: boolean;
release_url: string;
files: IToolReleaseFile[];
}
export declare function _findMatch(versionSpec: string, stable: boolean, candidates: IToolRelease[], archFilter: string): Promise<IToolRelease | undefined>;
export declare function _getOsVersion(): string;
export declare function _readLinuxVersionFile(): string;
+106
View File
@@ -0,0 +1,106 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const semver = __importStar(require("semver"));
const core_1 = require("@actions/core");
// needs to be require for core node modules to be mocked
/* eslint @typescript-eslint/no-require-imports: 0 */
const os = require("os");
const cp = require("child_process");
const fs = require("fs");
function _findMatch(versionSpec, stable, candidates, archFilter) {
return __awaiter(this, void 0, void 0, function* () {
const platFilter = os.platform();
let result;
let match;
let file;
for (const candidate of candidates) {
const version = candidate.version;
core_1.debug(`check ${version} satisfies ${versionSpec}`);
if (semver.satisfies(version, versionSpec) &&
(!stable || candidate.stable === stable)) {
file = candidate.files.find(item => {
core_1.debug(`${item.arch}===${archFilter} && ${item.platform}===${platFilter}`);
let chk = item.arch === archFilter && item.platform === platFilter;
if (chk && item.platform_version) {
const osVersion = module.exports._getOsVersion();
if (osVersion === item.platform_version) {
chk = true;
}
else {
chk = semver.satisfies(osVersion, item.platform_version);
}
}
return chk;
});
if (file) {
core_1.debug(`matched ${candidate.version}`);
match = candidate;
break;
}
}
}
if (match && file) {
// clone since we're mutating the file list to be only the file that matches
result = Object.assign({}, match);
result.files = [file];
}
return result;
});
}
exports._findMatch = _findMatch;
function _getOsVersion() {
// TODO: add windows and other linux, arm variants
// right now filtering on version is only an ubuntu and macos scenario for tools we build for hosted (python)
const plat = os.platform();
let version = '';
if (plat === 'darwin') {
version = cp.execSync('sw_vers -productVersion').toString();
}
else if (plat === 'linux') {
// lsb_release process not in some containers, readfile
// Run cat /etc/lsb-release
// DISTRIB_ID=Ubuntu
// DISTRIB_RELEASE=18.04
// DISTRIB_CODENAME=bionic
// DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS"
const lsbContents = module.exports._readLinuxVersionFile();
if (lsbContents) {
const lines = lsbContents.split('\n');
for (const line of lines) {
const parts = line.split('=');
if (parts.length === 2 && parts[0].trim() === 'DISTRIB_RELEASE') {
version = parts[1].trim();
break;
}
}
}
}
return version;
}
exports._getOsVersion = _getOsVersion;
function _readLinuxVersionFile() {
const lsbFile = '/etc/lsb-release';
let contents = '';
if (fs.existsSync(lsbFile)) {
contents = fs.readFileSync(lsbFile).toString();
}
return contents;
}
exports._readLinuxVersionFile = _readLinuxVersionFile;
//# sourceMappingURL=manifest.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,+CAAgC;AAChC,wCAAmC;AAEnC,yDAAyD;AACzD,qDAAqD;AAErD,yBAAyB;AACzB,oCAAoC;AACpC,yBAAyB;AAqDzB,SAAsB,UAAU,CAC9B,WAAmB,EACnB,MAAe,EACf,UAA0B,EAC1B,UAAkB;;QAElB,MAAM,UAAU,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAA;QAEhC,IAAI,MAAgC,CAAA;QACpC,IAAI,KAA+B,CAAA;QAEnC,IAAI,IAAkC,CAAA;QACtC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE;YAClC,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAA;YAEjC,YAAK,CAAC,SAAS,OAAO,cAAc,WAAW,EAAE,CAAC,CAAA;YAClD,IACE,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC;gBACtC,CAAC,CAAC,MAAM,IAAI,SAAS,CAAC,MAAM,KAAK,MAAM,CAAC,EACxC;gBACA,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;oBACjC,YAAK,CACH,GAAG,IAAI,CAAC,IAAI,MAAM,UAAU,OAAO,IAAI,CAAC,QAAQ,MAAM,UAAU,EAAE,CACnE,CAAA;oBAED,IAAI,GAAG,GAAG,IAAI,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,CAAC,QAAQ,KAAK,UAAU,CAAA;oBAClE,IAAI,GAAG,IAAI,IAAI,CAAC,gBAAgB,EAAE;wBAChC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,CAAA;wBAEhD,IAAI,SAAS,KAAK,IAAI,CAAC,gBAAgB,EAAE;4BACvC,GAAG,GAAG,IAAI,CAAA;yBACX;6BAAM;4BACL,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAA;yBACzD;qBACF;oBAED,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAC,CAAA;gBAEF,IAAI,IAAI,EAAE;oBACR,YAAK,CAAC,WAAW,SAAS,CAAC,OAAO,EAAE,CAAC,CAAA;oBACrC,KAAK,GAAG,SAAS,CAAA;oBACjB,MAAK;iBACN;aACF;SACF;QAED,IAAI,KAAK,IAAI,IAAI,EAAE;YACjB,4EAA4E;YAC5E,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,CAAA;YACjC,MAAM,CAAC,KAAK,GAAG,CAAC,IAAI,CAAC,CAAA;SACtB;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAtDD,gCAsDC;AAED,SAAgB,aAAa;IAC3B,kDAAkD;IAClD,6GAA6G;IAC7G,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAA;IAC1B,IAAI,OAAO,GAAG,EAAE,CAAA;IAEhB,IAAI,IAAI,KAAK,QAAQ,EAAE;QACrB,OAAO,GAAG,EAAE,CAAC,QAAQ,CAAC,yBAAyB,CAAC,CAAC,QAAQ,EAAE,CAAA;KAC5D;SAAM,IAAI,IAAI,KAAK,OAAO,EAAE;QAC3B,uDAAuD;QACvD,2BAA2B;QAC3B,oBAAoB;QACpB,wBAAwB;QACxB,0BAA0B;QAC1B,2CAA2C;QAC3C,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,qBAAqB,EAAE,CAAA;QAC1D,IAAI,WAAW,EAAE;YACf,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;YACrC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;gBACxB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;gBAC7B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,iBAAiB,EAAE;oBAC/D,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;oBACzB,MAAK;iBACN;aACF;SACF;KACF;IAED,OAAO,OAAO,CAAA;AAChB,CAAC;AA7BD,sCA6BC;AAED,SAAgB,qBAAqB;IACnC,MAAM,OAAO,GAAG,kBAAkB,CAAA;IAClC,IAAI,QAAQ,GAAG,EAAE,CAAA;IAEjB,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;QAC1B,QAAQ,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;KAC/C;IAED,OAAO,QAAQ,CAAA;AACjB,CAAC;AATD,sDASC"}
+12
View File
@@ -0,0 +1,12 @@
/**
* Internal class for retries
*/
export declare class RetryHelper {
private maxAttempts;
private minSeconds;
private maxSeconds;
constructor(maxAttempts: number, minSeconds: number, maxSeconds: number);
execute<T>(action: () => Promise<T>, isRetryable?: (e: Error) => boolean): Promise<T>;
private getSleepAmount;
private sleep;
}
+70
View File
@@ -0,0 +1,70 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
/**
* Internal class for retries
*/
class RetryHelper {
constructor(maxAttempts, minSeconds, maxSeconds) {
if (maxAttempts < 1) {
throw new Error('max attempts should be greater than or equal to 1');
}
this.maxAttempts = maxAttempts;
this.minSeconds = Math.floor(minSeconds);
this.maxSeconds = Math.floor(maxSeconds);
if (this.minSeconds > this.maxSeconds) {
throw new Error('min seconds should be less than or equal to max seconds');
}
}
execute(action, isRetryable) {
return __awaiter(this, void 0, void 0, function* () {
let attempt = 1;
while (attempt < this.maxAttempts) {
// Try
try {
return yield action();
}
catch (err) {
if (isRetryable && !isRetryable(err)) {
throw err;
}
core.info(err.message);
}
// Sleep
const seconds = this.getSleepAmount();
core.info(`Waiting ${seconds} seconds before trying again`);
yield this.sleep(seconds);
attempt++;
}
// Last attempt
return yield action();
});
}
getSleepAmount() {
return (Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) +
this.minSeconds);
}
sleep(seconds) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
});
}
}
exports.RetryHelper = RetryHelper;
//# sourceMappingURL=retry-helper.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"retry-helper.js","sourceRoot":"","sources":["../src/retry-helper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,oDAAqC;AAErC;;GAEG;AACH,MAAa,WAAW;IAKtB,YAAY,WAAmB,EAAE,UAAkB,EAAE,UAAkB;QACrE,IAAI,WAAW,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAA;SACrE;QAED,IAAI,CAAC,WAAW,GAAG,WAAW,CAAA;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACxC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;QACxC,IAAI,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;SAC3E;IACH,CAAC;IAEK,OAAO,CACX,MAAwB,EACxB,WAAmC;;YAEnC,IAAI,OAAO,GAAG,CAAC,CAAA;YACf,OAAO,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE;gBACjC,MAAM;gBACN,IAAI;oBACF,OAAO,MAAM,MAAM,EAAE,CAAA;iBACtB;gBAAC,OAAO,GAAG,EAAE;oBACZ,IAAI,WAAW,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE;wBACpC,MAAM,GAAG,CAAA;qBACV;oBAED,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;iBACvB;gBAED,QAAQ;gBACR,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,EAAE,CAAA;gBACrC,IAAI,CAAC,IAAI,CAAC,WAAW,OAAO,8BAA8B,CAAC,CAAA;gBAC3D,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;gBACzB,OAAO,EAAE,CAAA;aACV;YAED,eAAe;YACf,OAAO,MAAM,MAAM,EAAE,CAAA;QACvB,CAAC;KAAA;IAEO,cAAc;QACpB,OAAO,CACL,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;YACnE,IAAI,CAAC,UAAU,CAChB,CAAA;IACH,CAAC;IAEa,KAAK,CAAC,OAAe;;YACjC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC,CAAA;QACpE,CAAC;KAAA;CACF;AAxDD,kCAwDC"}
+20 -4
View File
@@ -1,3 +1,4 @@
import * as mm from './manifest';
export declare class HTTPError extends Error { export declare class HTTPError extends Error {
readonly httpStatusCode: number | undefined; readonly httpStatusCode: number | undefined;
constructor(httpStatusCode: number | undefined); constructor(httpStatusCode: number | undefined);
@@ -6,9 +7,11 @@ export declare class HTTPError extends Error {
* Download a tool from an url and stream it into a file * Download a tool from an url and stream it into a file
* *
* @param url url of tool to download * @param url url of tool to download
* @param dest path to download tool
* @param auth authorization header
* @returns path to downloaded tool * @returns path to downloaded tool
*/ */
export declare function downloadTool(url: string): Promise<string>; export declare function downloadTool(url: string, dest?: string, auth?: string): Promise<string>;
/** /**
* Extract a .7z file * Extract a .7z file
* *
@@ -26,14 +29,23 @@ export declare function downloadTool(url: string): Promise<string>;
*/ */
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>; export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
/** /**
* Extract a tar * Extract a compressed tar archive
* *
* @param file path to the tar * @param file path to the tar
* @param dest destination directory. Optional. * @param dest destination directory. Optional.
* @param flags flags for the tar. Optional. * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
* @returns path to the destination directory * @returns path to the destination directory
*/ */
export declare function extractTar(file: string, dest?: string, flags?: string): Promise<string>; export declare function extractTar(file: string, dest?: string, flags?: string | string[]): Promise<string>;
/**
* Extract a xar compatible archive
*
* @param file path to the archive
* @param dest destination directory. Optional.
* @param flags flags for the xar. Optional.
* @returns path to the destination directory
*/
export declare function extractXar(file: string, dest?: string, flags?: string | string[]): Promise<string>;
/** /**
* Extract a zip * Extract a zip
* *
@@ -77,3 +89,7 @@ export declare function find(toolName: string, versionSpec: string, arch?: strin
* @param arch optional arch. defaults to arch of computer * @param arch optional arch. defaults to arch of computer
*/ */
export declare function findAllVersions(toolName: string, arch?: string): string[]; export declare function findAllVersions(toolName: string, arch?: string): string[];
export declare type IToolRelease = mm.IToolRelease;
export declare type IToolReleaseFile = mm.IToolReleaseFile;
export declare function getManifestFromRepo(owner: string, repo: string, auth?: string, branch?: string): Promise<IToolRelease[]>;
export declare function findFromManifest(versionSpec: string, stable: boolean, manifest: IToolRelease[], archFilter?: string): Promise<IToolRelease | undefined>;
+260 -103
View File
@@ -8,17 +8,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const core = require("@actions/core"); const core = __importStar(require("@actions/core"));
const io = require("@actions/io"); const io = __importStar(require("@actions/io"));
const fs = require("fs"); const fs = __importStar(require("fs"));
const os = require("os"); const mm = __importStar(require("./manifest"));
const path = require("path"); const os = __importStar(require("os"));
const httpm = require("typed-rest-client/HttpClient"); const path = __importStar(require("path"));
const semver = require("semver"); const httpm = __importStar(require("@actions/http-client"));
const uuidV4 = require("uuid/v4"); const semver = __importStar(require("semver"));
const stream = __importStar(require("stream"));
const util = __importStar(require("util"));
const v4_1 = __importDefault(require("uuid/v4"));
const exec_1 = require("@actions/exec/lib/exec"); const exec_1 = require("@actions/exec/lib/exec");
const assert_1 = require("assert"); const assert_1 = require("assert");
const retry_helper_1 = require("./retry-helper");
class HTTPError extends Error { class HTTPError extends Error {
constructor(httpStatusCode) { constructor(httpStatusCode) {
super(`Unexpected HTTP response: ${httpStatusCode}`); super(`Unexpected HTTP response: ${httpStatusCode}`);
@@ -28,86 +42,90 @@ class HTTPError extends Error {
} }
exports.HTTPError = HTTPError; exports.HTTPError = HTTPError;
const IS_WINDOWS = process.platform === 'win32'; const IS_WINDOWS = process.platform === 'win32';
const IS_MAC = process.platform === 'darwin';
const userAgent = 'actions/tool-cache'; const userAgent = 'actions/tool-cache';
// On load grab temp directory and cache directory and remove them from env (currently don't want to expose this)
let tempDirectory = process.env['RUNNER_TEMP'] || '';
let cacheRoot = process.env['RUNNER_TOOL_CACHE'] || '';
// If directories not found, place them in common temp locations
if (!tempDirectory || !cacheRoot) {
let baseLocation;
if (IS_WINDOWS) {
// On windows use the USERPROFILE env variable
baseLocation = process.env['USERPROFILE'] || 'C:\\';
}
else {
if (process.platform === 'darwin') {
baseLocation = '/Users';
}
else {
baseLocation = '/home';
}
}
if (!tempDirectory) {
tempDirectory = path.join(baseLocation, 'actions', 'temp');
}
if (!cacheRoot) {
cacheRoot = path.join(baseLocation, 'actions', 'cache');
}
}
/** /**
* Download a tool from an url and stream it into a file * Download a tool from an url and stream it into a file
* *
* @param url url of tool to download * @param url url of tool to download
* @param dest path to download tool
* @param auth authorization header
* @returns path to downloaded tool * @returns path to downloaded tool
*/ */
function downloadTool(url) { function downloadTool(url, dest, auth) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
// Wrap in a promise so that we can resolve from within stream callbacks dest = dest || path.join(_getTempDirectory(), v4_1.default());
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { yield io.mkdirP(path.dirname(dest));
try { core.debug(`Downloading ${url}`);
const http = new httpm.HttpClient(userAgent, [], { core.debug(`Destination ${dest}`);
allowRetries: true, const maxAttempts = 3;
maxRetries: 3 const minSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MIN_SECONDS', 10);
}); const maxSeconds = _getGlobal('TEST_DOWNLOAD_TOOL_RETRY_MAX_SECONDS', 20);
const destPath = path.join(tempDirectory, uuidV4()); const retryHelper = new retry_helper_1.RetryHelper(maxAttempts, minSeconds, maxSeconds);
yield io.mkdirP(tempDirectory); return yield retryHelper.execute(() => __awaiter(this, void 0, void 0, function* () {
core.debug(`Downloading ${url}`); return yield downloadToolAttempt(url, dest || '', auth);
core.debug(`Downloading ${destPath}`); }), (err) => {
if (fs.existsSync(destPath)) { if (err instanceof HTTPError && err.httpStatusCode) {
throw new Error(`Destination file path ${destPath} already exists`); // Don't retry anything less than 500, except 408 Request Timeout and 429 Too Many Requests
if (err.httpStatusCode < 500 &&
err.httpStatusCode !== 408 &&
err.httpStatusCode !== 429) {
return false;
} }
const response = yield http.get(url);
if (response.message.statusCode !== 200) {
const err = new HTTPError(response.message.statusCode);
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
throw err;
}
const file = fs.createWriteStream(destPath);
file.on('open', () => __awaiter(this, void 0, void 0, function* () {
try {
const stream = response.message.pipe(file);
stream.on('close', () => {
core.debug('download complete');
resolve(destPath);
});
}
catch (err) {
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
reject(err);
}
}));
file.on('error', err => {
file.end();
reject(err);
});
} }
catch (err) { // Otherwise retry
reject(err); return true;
} });
}));
}); });
} }
exports.downloadTool = downloadTool; exports.downloadTool = downloadTool;
function downloadToolAttempt(url, dest, auth) {
return __awaiter(this, void 0, void 0, function* () {
if (fs.existsSync(dest)) {
throw new Error(`Destination file path ${dest} already exists`);
}
// Get the response headers
const http = new httpm.HttpClient(userAgent, [], {
allowRetries: false
});
let headers;
if (auth) {
core.debug('set auth');
headers = {
authorization: auth
};
}
const response = yield http.get(url, headers);
if (response.message.statusCode !== 200) {
const err = new HTTPError(response.message.statusCode);
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
throw err;
}
// Download the response body
const pipeline = util.promisify(stream.pipeline);
const responseMessageFactory = _getGlobal('TEST_DOWNLOAD_TOOL_RESPONSE_MESSAGE_FACTORY', () => response.message);
const readStream = responseMessageFactory();
let succeeded = false;
try {
yield pipeline(readStream, fs.createWriteStream(dest));
core.debug('download complete');
succeeded = true;
return dest;
}
finally {
// Error, delete dest before retry
if (!succeeded) {
core.debug('download failed');
try {
yield io.rmRF(dest);
}
catch (err) {
core.debug(`Failed to delete '${dest}'. ${err.message}`);
}
}
}
});
}
/** /**
* Extract a .7z file * Extract a .7z file
* *
@@ -127,14 +145,15 @@ function extract7z(file, dest, _7zPath) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS'); assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
assert_1.ok(file, 'parameter "file" is required'); assert_1.ok(file, 'parameter "file" is required');
dest = dest || (yield _createExtractFolder(dest)); dest = yield _createExtractFolder(dest);
const originalCwd = process.cwd(); const originalCwd = process.cwd();
process.chdir(dest); process.chdir(dest);
if (_7zPath) { if (_7zPath) {
try { try {
const logLevel = core.isDebug() ? '-bb1' : '-bb0';
const args = [ const args = [
'x', 'x',
'-bb1', logLevel,
'-bd', '-bd',
'-sccUTF-8', '-sccUTF-8',
file file
@@ -182,11 +201,11 @@ function extract7z(file, dest, _7zPath) {
} }
exports.extract7z = extract7z; exports.extract7z = extract7z;
/** /**
* Extract a tar * Extract a compressed tar archive
* *
* @param file path to the tar * @param file path to the tar
* @param dest destination directory. Optional. * @param dest destination directory. Optional.
* @param flags flags for the tar. Optional. * @param flags flags for the tar command to use for extraction. Defaults to 'xz' (extracting gzipped tars). Optional.
* @returns path to the destination directory * @returns path to the destination directory
*/ */
function extractTar(file, dest, flags = 'xz') { function extractTar(file, dest, flags = 'xz') {
@@ -194,13 +213,81 @@ function extractTar(file, dest, flags = 'xz') {
if (!file) { if (!file) {
throw new Error("parameter 'file' is required"); throw new Error("parameter 'file' is required");
} }
dest = dest || (yield _createExtractFolder(dest)); // Create dest
const tarPath = yield io.which('tar', true); dest = yield _createExtractFolder(dest);
yield exec_1.exec(`"${tarPath}"`, [flags, '-C', dest, '-f', file]); // Determine whether GNU tar
core.debug('Checking tar --version');
let versionOutput = '';
yield exec_1.exec('tar --version', [], {
ignoreReturnCode: true,
silent: true,
listeners: {
stdout: (data) => (versionOutput += data.toString()),
stderr: (data) => (versionOutput += data.toString())
}
});
core.debug(versionOutput.trim());
const isGnuTar = versionOutput.toUpperCase().includes('GNU TAR');
// Initialize args
let args;
if (flags instanceof Array) {
args = flags;
}
else {
args = [flags];
}
if (core.isDebug() && !flags.includes('v')) {
args.push('-v');
}
let destArg = dest;
let fileArg = file;
if (IS_WINDOWS && isGnuTar) {
args.push('--force-local');
destArg = dest.replace(/\\/g, '/');
// Technically only the dest needs to have `/` but for aesthetic consistency
// convert slashes in the file arg too.
fileArg = file.replace(/\\/g, '/');
}
if (isGnuTar) {
// Suppress warnings when using GNU tar to extract archives created by BSD tar
args.push('--warning=no-unknown-keyword');
}
args.push('-C', destArg, '-f', fileArg);
yield exec_1.exec(`tar`, args);
return dest; return dest;
}); });
} }
exports.extractTar = extractTar; exports.extractTar = extractTar;
/**
* Extract a xar compatible archive
*
* @param file path to the archive
* @param dest destination directory. Optional.
* @param flags flags for the xar. Optional.
* @returns path to the destination directory
*/
function extractXar(file, dest, flags = []) {
return __awaiter(this, void 0, void 0, function* () {
assert_1.ok(IS_MAC, 'extractXar() not supported on current OS');
assert_1.ok(file, 'parameter "file" is required');
dest = yield _createExtractFolder(dest);
let args;
if (flags instanceof Array) {
args = flags;
}
else {
args = [flags];
}
args.push('-x', '-C', dest, '-f', file);
if (core.isDebug()) {
args.push('-v');
}
const xarPath = yield io.which('xar', true);
yield exec_1.exec(`"${xarPath}"`, _unique(args));
return dest;
});
}
exports.extractXar = extractXar;
/** /**
* Extract a zip * Extract a zip
* *
@@ -213,17 +300,12 @@ function extractZip(file, dest) {
if (!file) { if (!file) {
throw new Error("parameter 'file' is required"); throw new Error("parameter 'file' is required");
} }
dest = dest || (yield _createExtractFolder(dest)); dest = yield _createExtractFolder(dest);
if (IS_WINDOWS) { if (IS_WINDOWS) {
yield extractZipWin(file, dest); yield extractZipWin(file, dest);
} }
else { else {
if (process.platform === 'darwin') { yield extractZipNix(file, dest);
yield extractZipDarwin(file, dest);
}
else {
yield extractZipNix(file, dest);
}
} }
return dest; return dest;
}); });
@@ -236,7 +318,7 @@ function extractZipWin(file, dest) {
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ''); const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`; const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
// run powershell // run powershell
const powershellPath = yield io.which('powershell'); const powershellPath = yield io.which('powershell', true);
const args = [ const args = [
'-NoLogo', '-NoLogo',
'-Sta', '-Sta',
@@ -252,14 +334,12 @@ function extractZipWin(file, dest) {
} }
function extractZipNix(file, dest) { function extractZipNix(file, dest) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const unzipPath = path.join(__dirname, '..', 'scripts', 'externals', 'unzip'); const unzipPath = yield io.which('unzip', true);
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest }); const args = [file];
}); if (!core.isDebug()) {
} args.unshift('-q');
function extractZipDarwin(file, dest) { }
return __awaiter(this, void 0, void 0, function* () { yield exec_1.exec(`"${unzipPath}"`, args, { cwd: dest });
const unzipPath = path.join(__dirname, '..', 'scripts', 'externals', 'unzip-darwin');
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
}); });
} }
/** /**
@@ -350,7 +430,7 @@ function find(toolName, versionSpec, arch) {
let toolPath = ''; let toolPath = '';
if (versionSpec) { if (versionSpec) {
versionSpec = semver.clean(versionSpec) || ''; versionSpec = semver.clean(versionSpec) || '';
const cachePath = path.join(cacheRoot, toolName, versionSpec, arch); const cachePath = path.join(_getCacheDirectory(), toolName, versionSpec, arch);
core.debug(`checking cache: ${cachePath}`); core.debug(`checking cache: ${cachePath}`);
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) { if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`); core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
@@ -372,7 +452,7 @@ exports.find = find;
function findAllVersions(toolName, arch) { function findAllVersions(toolName, arch) {
const versions = []; const versions = [];
arch = arch || os.arch(); arch = arch || os.arch();
const toolPath = path.join(cacheRoot, toolName); const toolPath = path.join(_getCacheDirectory(), toolName);
if (fs.existsSync(toolPath)) { if (fs.existsSync(toolPath)) {
const children = fs.readdirSync(toolPath); const children = fs.readdirSync(toolPath);
for (const child of children) { for (const child of children) {
@@ -387,11 +467,56 @@ function findAllVersions(toolName, arch) {
return versions; return versions;
} }
exports.findAllVersions = findAllVersions; exports.findAllVersions = findAllVersions;
function getManifestFromRepo(owner, repo, auth, branch = 'master') {
return __awaiter(this, void 0, void 0, function* () {
let releases = [];
const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}`;
const http = new httpm.HttpClient('tool-cache');
const headers = {};
if (auth) {
core.debug('set auth');
headers.authorization = auth;
}
const response = yield http.getJson(treeUrl, headers);
if (!response.result) {
return releases;
}
let manifestUrl = '';
for (const item of response.result.tree) {
if (item.path === 'versions-manifest.json') {
manifestUrl = item.url;
break;
}
}
headers['accept'] = 'application/vnd.github.VERSION.raw';
let versionsRaw = yield (yield http.get(manifestUrl, headers)).readBody();
if (versionsRaw) {
// shouldn't be needed but protects against invalid json saved with BOM
versionsRaw = versionsRaw.replace(/^\uFEFF/, '');
try {
releases = JSON.parse(versionsRaw);
}
catch (_a) {
core.debug('Invalid json');
}
}
return releases;
});
}
exports.getManifestFromRepo = getManifestFromRepo;
function findFromManifest(versionSpec, stable, manifest, archFilter = os.arch()) {
return __awaiter(this, void 0, void 0, function* () {
// wrap the internal impl
const match = yield mm._findMatch(versionSpec, stable, manifest, archFilter);
return match;
});
}
exports.findFromManifest = findFromManifest;
function _createExtractFolder(dest) { function _createExtractFolder(dest) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
if (!dest) { if (!dest) {
// create a temp dir // create a temp dir
dest = path.join(tempDirectory, uuidV4()); dest = path.join(_getTempDirectory(), v4_1.default());
} }
yield io.mkdirP(dest); yield io.mkdirP(dest);
return dest; return dest;
@@ -399,7 +524,7 @@ function _createExtractFolder(dest) {
} }
function _createToolPath(tool, version, arch) { function _createToolPath(tool, version, arch) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || ''); const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || '');
core.debug(`destination ${folderPath}`); core.debug(`destination ${folderPath}`);
const markerPath = `${folderPath}.complete`; const markerPath = `${folderPath}.complete`;
yield io.rmRF(folderPath); yield io.rmRF(folderPath);
@@ -409,7 +534,7 @@ function _createToolPath(tool, version, arch) {
}); });
} }
function _completeToolPath(tool, version, arch) { function _completeToolPath(tool, version, arch) {
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || ''); const folderPath = path.join(_getCacheDirectory(), tool, semver.clean(version) || version, arch || '');
const markerPath = `${folderPath}.complete`; const markerPath = `${folderPath}.complete`;
fs.writeFileSync(markerPath, ''); fs.writeFileSync(markerPath, '');
core.debug('finished caching tool'); core.debug('finished caching tool');
@@ -446,4 +571,36 @@ function _evaluateVersions(versions, versionSpec) {
} }
return version; return version;
} }
/**
* Gets RUNNER_TOOL_CACHE
*/
function _getCacheDirectory() {
const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || '';
assert_1.ok(cacheDirectory, 'Expected RUNNER_TOOL_CACHE to be defined');
return cacheDirectory;
}
/**
* Gets RUNNER_TEMP
*/
function _getTempDirectory() {
const tempDirectory = process.env['RUNNER_TEMP'] || '';
assert_1.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined');
return tempDirectory;
}
/**
* Gets a global variable
*/
function _getGlobal(key, defaultValue) {
/* eslint-disable @typescript-eslint/no-explicit-any */
const value = global[key];
/* eslint-enable @typescript-eslint/no-explicit-any */
return value !== undefined ? value : defaultValue;
}
/**
* Returns an array of unique values.
* @param values Values to make unique.
*/
function _unique(values) {
return Array.from(new Set(values));
}
//# sourceMappingURL=tool-cache.js.map //# sourceMappingURL=tool-cache.js.map
File diff suppressed because one or more lines are too long
+21 -22
View File
@@ -1,44 +1,41 @@
{ {
"_args": [ "_from": "@actions/tool-cache@1.6.0",
[ "_id": "@actions/tool-cache@1.6.0",
"@actions/tool-cache@1.1.1",
"E:\\k8s-actions\\deploy\\k8s-deploy"
]
],
"_from": "@actions/tool-cache@1.1.1",
"_id": "@actions/tool-cache@1.1.1",
"_inBundle": false, "_inBundle": false,
"_integrity": "sha512-AILekrrj/L4N/5z5TGtUKVie4nKjxDioCgOEymyYxzPhGfjIxfE71tN2VTTpiICEWJ883rPRj2+WinTr1b6yVA==", "_integrity": "sha512-+fyEBImPD3m5I0o6DflCO0NHY180LPoX8Lo6y4Iez+V17kO8kfkH0VHxb8mUdmD6hn9dWA9Ch1JA20fXoIYUeQ==",
"_location": "/@actions/tool-cache", "_location": "/@actions/tool-cache",
"_phantomChildren": {}, "_phantomChildren": {},
"_requested": { "_requested": {
"type": "version", "type": "version",
"registry": true, "registry": true,
"raw": "@actions/tool-cache@1.1.1", "raw": "@actions/tool-cache@1.6.0",
"name": "@actions/tool-cache", "name": "@actions/tool-cache",
"escapedName": "@actions%2ftool-cache", "escapedName": "@actions%2ftool-cache",
"scope": "@actions", "scope": "@actions",
"rawSpec": "1.1.1", "rawSpec": "1.6.0",
"saveSpec": null, "saveSpec": null,
"fetchSpec": "1.1.1" "fetchSpec": "1.6.0"
}, },
"_requiredBy": [ "_requiredBy": [
"/" "/"
], ],
"_resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.1.1.tgz", "_resolved": "https://registry.npmjs.org/@actions/tool-cache/-/tool-cache-1.6.0.tgz",
"_spec": "1.1.1", "_shasum": "5b425db2d642df65dd0d6bcec0d84dcdbca3f80d",
"_where": "E:\\k8s-actions\\deploy\\k8s-deploy", "_spec": "@actions/tool-cache@1.6.0",
"_where": "/Users/aj/repos/k8s-deploy",
"bugs": { "bugs": {
"url": "https://github.com/actions/toolkit/issues" "url": "https://github.com/actions/toolkit/issues"
}, },
"bundleDependencies": false,
"dependencies": { "dependencies": {
"@actions/core": "^1.1.0", "@actions/core": "^1.2.3",
"@actions/exec": "^1.0.1", "@actions/exec": "^1.0.0",
"@actions/http-client": "^1.0.8",
"@actions/io": "^1.0.1", "@actions/io": "^1.0.1",
"semver": "^6.1.0", "semver": "^6.1.0",
"typed-rest-client": "^1.4.0",
"uuid": "^3.3.2" "uuid": "^3.3.2"
}, },
"deprecated": false,
"description": "Actions tool-cache lib", "description": "Actions tool-cache lib",
"devDependencies": { "devDependencies": {
"@types/nock": "^10.0.3", "@types/nock": "^10.0.3",
@@ -54,8 +51,7 @@
"lib", "lib",
"scripts" "scripts"
], ],
"gitHead": "a2ab4bcf78e4f7080f0d45856e6eeba16f0bbc52", "homepage": "https://github.com/actions/toolkit/tree/master/packages/tool-cache",
"homepage": "https://github.com/actions/toolkit/tree/master/packages/exec",
"keywords": [ "keywords": [
"github", "github",
"actions", "actions",
@@ -69,11 +65,14 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/actions/toolkit.git" "url": "git+https://github.com/actions/toolkit.git",
"directory": "packages/tool-cache"
}, },
"scripts": { "scripts": {
"audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json",
"test": "echo \"Error: run tests from root\" && exit 1", "test": "echo \"Error: run tests from root\" && exit 1",
"tsc": "tsc" "tsc": "tsc"
}, },
"version": "1.1.1" "types": "lib/tool-cache.d.ts",
"version": "1.6.0"
} }
Binary file not shown.
Binary file not shown.
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

Some files were not shown because too many files have changed in this diff Show More