├── AUTHORS ├── Architecture.png ├── CONTRIBUTING.md ├── Configuration.yaml ├── Dockerfile ├── LICENSE ├── ListProjects.sh ├── README.md ├── build.sh ├── deploy.sh ├── emailNotification.json ├── logBasedAlerting.json ├── requirements.txt ├── setup.sh └── supportTicket.py /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the list of project authors for copyright purposes. 2 | # 3 | # This does not necessarily list everyone who has contributed code, since in 4 | # some cases, their employer may be the copyright holder. To see the full list 5 | # of contributors, see the revision history in source control. 6 | 7 | Google LLC 8 | Julie Ngo -------------------------------------------------------------------------------- /Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/support-case-notifications/cb755c1a2efe5996a3540211ab34ac14e8da9bfa/Architecture.png -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 16 | 17 | # How to Contribute 18 | 19 | We'd love to accept your patches and contributions to this project. 20 | 21 | ## Before you begin 22 | 23 | ### Sign our Contributor License Agreement 24 | 25 | Contributions to this project must be accompanied by a 26 | [Contributor License Agreement](https://cla.developers.google.com/about) (CLA). 27 | You (or your employer) retain the copyright to your contribution; this simply 28 | gives us permission to use and redistribute your contributions as part of the 29 | project. 30 | 31 | If you or your current employer have already signed the Google CLA (even if it 32 | was for a different project), you probably don't need to do it again. 33 | 34 | Visit to see your current agreements or to 35 | sign a new one. 36 | 37 | ### Review our Community Guidelines 38 | 39 | This project follows 40 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 41 | 42 | ## Contribution process 43 | 44 | ### Code Reviews 45 | 46 | All submissions, including submissions by project members, require review. We 47 | use GitHub pull requests for this purpose. Consult 48 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 49 | information on using pull requests. -------------------------------------------------------------------------------- /Configuration.yaml: -------------------------------------------------------------------------------- 1 | #Copyright 2023 Google LLC 2 | # 3 | #Licensed under the Apache License, Version 2.0 (the "License"); 4 | #you may not use this file except in compliance with the License. 5 | #You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | #Unless required by applicable law or agreed to in writing, software 10 | #distributed under the License is distributed on an "AS IS" BASIS, 11 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | #See the License for the specific language governing permissions and 13 | #limitations under the License. 14 | 15 | #Instructions: 16 | #1. Replace the project ID that you would like the notifications to originate from 17 | #2. Replace the organization ID that this project falls under 18 | # 19 | #3. If you would like to get notified about new cases only from the project level, 20 | #replace the onlyProject value with True 21 | # 22 | #4. If you would like to get notified about new cases from the organization level, 23 | #including all projects that fall within this organization, keep the onlyProject value with False 24 | 25 | project: "example-project-id" 26 | 27 | organization: "example-org-id" 28 | 29 | onlyProject: "False" 30 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | #Copyright 2023 Google LLC 2 | # 3 | #Licensed under the Apache License, Version 2.0 (the "License"); 4 | #you may not use this file except in compliance with the License. 5 | #You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | #Unless required by applicable law or agreed to in writing, software 10 | #distributed under the License is distributed on an "AS IS" BASIS, 11 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | #See the License for the specific language governing permissions and 13 | #limitations under the License. 14 | 15 | FROM python:3 16 | WORKDIR /app 17 | 18 | COPY requirements.txt ./ 19 | RUN pip install -r requirements.txt 20 | COPY . . 21 | 22 | RUN export GOOGLE_APPLICATION_CREDENTIALS='key.json' 23 | 24 | CMD [ "python", "./supportTicket.py" ] 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /ListProjects.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | #Copyright 2023 Google LLC 3 | # 4 | #Licensed under the Apache License, Version 2.0 (the "License"); 5 | #you may not use this file except in compliance with the License. 6 | #You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | #Unless required by applicable law or agreed to in writing, software 11 | #distributed under the License is distributed on an "AS IS" BASIS, 12 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | #See the License for the specific language governing permissions and 14 | #limitations under the License. 15 | 16 | # Required permission: roles/resourcemanager.folderViewer 17 | #Declare functions 18 | function getProjects() { 19 | gcloud projects list --filter="parent.id=$1" --format="value(PROJECT_ID)" >> organizationsList.txt 20 | } 21 | function getFolders() { 22 | if [ -z $1 ] 23 | then 24 | break 25 | else 26 | getProjects $i # Get projects at the current folder level 27 | for i in $(gcloud resource-manager folders list --folder="$1" --format="value(ID)"); do 28 | getFolders $i # Recurse to iterate into child folders 29 | done 30 | fi 31 | } 32 | 33 | gcloud projects list --filter=$1 --format="value(PROJECT_ID)" >> organizationsList.txt 34 | for i in $(gcloud resource-manager folders list --organization=$1 --format="value(ID)"); do 35 | getFolders $i 36 | done 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 16 | # GCP Cloud Run Module for Support Case Creation Notifications 17 | Containerized notification system for whenever a new support case is opened within your project or organization. The Cloud Scheduler will run every 10 minutes by default, triggering the Cloud Run job. The Cloud Run job will check if there are any new support cases and trigger the alerting policy, which will send a notification to the user. 18 | 19 | ![Architecture](Architecture.png) 20 | 21 | ## Disclaimer 22 | 23 | 1. This is not an officially supported Google product. 24 | 2. Proper testing should be done before running this tool in production. 25 | 3. Standard, Enhanced, or Premium support must be enabled for case creation and Support API usage 26 | 4. This solution assumes that the user has been assigned the appropriate IAM roles 27 | 28 | ## Licensing 29 | This sample code is made available under Apache 2 license. See the [LICENSE](./LICENSE) file for more details. 30 | 31 | ## GCP Costs 32 | 1. [Cloud Run Invocation](https://cloud.google.com/run/pricing#tables), usually free 33 | 2. [Cloud Scheduler Jobs](https://cloud.google.com/scheduler/pricing) for running the script in intervals. 34 | 3. [Customer Care pricing](https://cloud.google.com/support) for Standard, Enhanced, or Premium Support 35 | 4. [Cloud Logging and monitoring](https://cloud.google.com/stackdriver/pricing) for alerts when a new case is opened. 36 | 5. [Cloud Storage](https://cloud.google.com/storage/pricing) for retrieval and writing to a textfile stored in storage. 37 | 38 | ## Installation Instructions 39 | ### Prerequisites 40 | 1. Clone the git repo using `git clone REPO` 41 | 2. In the Configuration.yaml file: 42 | - Replace the "example-project-id" with your project ID 43 | - Replace the "example-org-id" with your organization ID 44 | - If you would like to receive notifications from new support cases at the project level, replace the False with True. Otherwise, if you would like to receive notifications from new support cases at the organization level, leave it as False. 45 | 3. Allow execution permissions with `chmod +x setup.sh build.sh deploy.sh ListProjects.sh` 46 | 4. Export the project ID `export PROJECT_ID=$(gcloud config get-value project)` 47 | 5. Creating a notification channel (skip this step if you already have a notification channel you would like to use): 48 | - Update the "example@example.com" with your email in `emailNotification.json` file 49 | - Run `gcloud beta monitoring channels create --channel-content-from-file="emailNotification.json"` 50 | 6. Update the alert policy: 51 | - List the alerts with `gcloud alpha monitoring channels list` 52 | - Replace the "notificationsChannel" value (line 26) with the name of the notification channel you would like to use 53 | 7. (Optional) Change the frequency that the script is run. The script runs every 10 minutes by default 54 | - In deploy.sh change the FREQUENCY variable (line 18) 55 | 56 | ### Run the scripts 57 | 1. Setup the service accounts and permissions by running `./setup.sh [ORGANIZATION_ID]` (Replace with your organization ID) 58 | 2. Containerize the application by running `./build.sh` 59 | 3. Deploy and create the alerting policy by running `./deploy.sh` 60 | 61 | You're done! You will receive notifications whenever a new support case is opened. 62 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Copyright 2023 Google LLC 3 | # 4 | #Licensed under the Apache License, Version 2.0 (the "License"); 5 | #you may not use this file except in compliance with the License. 6 | #You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | #Unless required by applicable law or agreed to in writing, software 11 | #distributed under the License is distributed on an "AS IS" BASIS, 12 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | #See the License for the specific language governing permissions and 14 | #limitations under the License. 15 | 16 | #Containerize the application with Cloud Run 17 | gcloud builds submit --tag gcr.io/${PROJECT_ID}/supportnotification -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Copyright 2023 Google LLC 3 | # 4 | #Licensed under the Apache License, Version 2.0 (the "License"); 5 | #you may not use this file except in compliance with the License. 6 | #You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | #Unless required by applicable law or agreed to in writing, software 11 | #distributed under the License is distributed on an "AS IS" BASIS, 12 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | #See the License for the specific language governing permissions and 14 | #limitations under the License. 15 | 16 | #Replace the frequency or region with your preference 17 | #The script will run by default every 10 minutes in us-central1 18 | FREQUENCY='*/10 * * * *' 19 | REGION='us-central1' 20 | 21 | #Create a Cloud Run job with the image 22 | gcloud beta run jobs create supportnotification --image gcr.io/${PROJECT_ID}/supportnotification --region ${REGION} 23 | 24 | #Create Cloud Scheduler job with the service account that has cloud run invoker permissions. 25 | gcloud scheduler jobs create http supportnotification-scheduler-trigger \ 26 | --location ${REGION} \ 27 | --schedule ${FREQUENCY}\ 28 | --uri "https://${REGION}-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/${PROJECT_ID}/jobs/supportnotification:run" \ 29 | --http-method POST \ 30 | --oauth-service-account-email sa-support-notif-scheduler@${PROJECT_ID}.iam.gserviceaccount.com 31 | 32 | -------------------------------------------------------------------------------- /emailNotification.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "email", 3 | "displayName": "Alert Support Ticket Notifications", 4 | "description": "Email channel for alert support ticket notifications", 5 | "labels": { 6 | "email_address": "example@example.com" 7 | } 8 | } -------------------------------------------------------------------------------- /logBasedAlerting.json: -------------------------------------------------------------------------------- 1 | { 2 | "displayName": "Support Case Opened Notification", 3 | "documentation": { 4 | "content": "Log-based alert in project ${project} detected a new support case being opened.", 5 | "mimeType": "text/markdown" 6 | }, 7 | 8 | "conditions": [ 9 | { 10 | "displayName": "New Support case created", 11 | "conditionMatchedLog": { 12 | "filter": textPayload="A new support case has been created.", 13 | }, 14 | } 15 | ], 16 | "combiner": "OR", 17 | 18 | "alertStrategy": { 19 | "notificationRateLimit": { 20 | "period": "300s" 21 | }, 22 | "autoClose": "604800s", 23 | }, 24 | 25 | "notificationChannels": [ 26 | "projects/example-project-id/notificationChannels/example-id" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyYaml 2 | google-apis-client-generator 3 | numpy 4 | google-cloud-storage 5 | google-cloud-logging -------------------------------------------------------------------------------- /setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Copyright 2023 Google LLC 3 | # 4 | #Licensed under the Apache License, Version 2.0 (the "License"); 5 | #you may not use this file except in compliance with the License. 6 | #You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | #Unless required by applicable law or agreed to in writing, software 11 | #distributed under the License is distributed on an "AS IS" BASIS, 12 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | #See the License for the specific language governing permissions and 14 | #limitations under the License. 15 | 16 | # Enable Cloud Run, and Cloud Scheduler, Cloud Logging, Cloud Support API, Cloud Monitoring 17 | gcloud services enable --project "${PROJECT_ID}" cloudbuild.googleapis.com run.googleapis.com cloudscheduler.googleapis.com cloudsupport.googleapis.com monitoring.googleapis.com logging.googleapis.com 18 | 19 | # Create Service Accounts for Cloud Scheduler Job and Support API 20 | gcloud iam service-accounts create sa-support-notif-scheduler --description="Run Cloud Run Service on behalf of Cloud Scheduler" 21 | gcloud iam service-accounts create sa-support-api --description="Call the support case API from within code" 22 | 23 | #Set permissions for Cloud Scheduler service account with Cloud Run invoker role 24 | gcloud projects add-iam-policy-binding ${PROJECT_ID} --member=serviceAccount:sa-support-notif-scheduler@${PROJECT_ID}.iam.gserviceaccount.com --role=roles/run.invoker 25 | 26 | # Set permissions for service account that will call the support API 27 | #organization viewer 28 | gcloud organizations add-iam-policy-binding \ 29 | organizations/$1 \ 30 | --role roles/resourcemanager.organizationViewer \ 31 | --member serviceAccount:sa-support-api@${PROJECT_ID}.iam.gserviceaccount.com 32 | #tech support editor 33 | gcloud organizations add-iam-policy-binding \ 34 | organizations/$1 \ 35 | --role roles/cloudsupport.techSupportEditor \ 36 | --member serviceAccount:sa-support-api@${PROJECT_ID}.iam.gserviceaccount.com 37 | #log writer permissions 38 | gcloud projects add-iam-policy-binding ${PROJECT_ID} --member=serviceAccount:sa-support-api@${PROJECT_ID}.iam.gserviceaccount.com --role=roles/logging.logWriter 39 | #resource folder viewer 40 | gcloud organizations add-iam-policy-binding $1 --member=serviceAccount:sa-support-api@${PROJECT_ID}.iam.gserviceaccount.com --role=roles/resourcemanager.folderViewer 41 | # Create a key for the Service Account for initiliazing the Cloud SDK 42 | gcloud iam service-accounts keys create --iam-account sa-support-api@${PROJECT_ID}.iam.gserviceaccount.com key.json 43 | 44 | #create bucket, TicketResult.txt and upload it to the bucket 45 | gsutil mb -p ${PROJECT_ID} -c NEARLINE -l US-EAST1 -b on "gs://${PROJECT_ID}-supportnotification/" 46 | touch TicketResults.txt 47 | echo -e "0\n0" > TicketResults.txt 48 | gsutil cp TicketResults.txt "gs://${PROJECT_ID}-supportnotification/" 49 | gcloud storage buckets add-iam-policy-binding gs://${PROJECT_ID}-supportnotification --member=serviceAccount:sa-support-api@${PROJECT_ID}.iam.gserviceaccount.com --role=roles/storage.objectAdmin 50 | 51 | #create new alert policy 52 | gcloud alpha monitoring policies create --policy-from-file="logBasedAlerting.json" -------------------------------------------------------------------------------- /supportTicket.py: -------------------------------------------------------------------------------- 1 | #Copyright 2023 Google LLC 2 | # 3 | #Licensed under the Apache License, Version 2.0 (the "License"); 4 | #you may not use this file except in compliance with the License. 5 | #You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | #Unless required by applicable law or agreed to in writing, software 10 | #distributed under the License is distributed on an "AS IS" BASIS, 11 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | #See the License for the specific language governing permissions and 13 | #limitations under the License. 14 | 15 | import googleapiclient.discovery 16 | import yaml 17 | from numpy import loadtxt 18 | import subprocess 19 | from google.cloud import storage 20 | import google.cloud.logging 21 | import os 22 | 23 | #log event 24 | def logEvent(): 25 | logging_client = google.cloud.logging.Client() 26 | log_name = "supportLog" 27 | logger = logging_client.logger(log_name) 28 | text = "A new support case has been created." 29 | logger.log_text(text, severity="WARNING") 30 | 31 | #read and parse configuration file 32 | def readConfigFile(IDs): 33 | with open('Configuration.yaml') as file: 34 | try: 35 | databaseConfig = yaml.safe_load(file) 36 | IDs["project"] = databaseConfig["project"] 37 | IDs["organization"] = databaseConfig["organization"] 38 | IDs["onlyProject"] = databaseConfig["onlyProject"] 39 | except yaml.YAMLError as exc: 40 | print(exc) 41 | 42 | def generateProjectIDs(organizationID): 43 | subprocess.check_call(["./ListProjects.sh " + organizationID],shell=True) 44 | 45 | #Checks if the current number of tickets match the old results. Returns True if should send email, False otherwise 46 | def sendEmail(closed, openNum, fileName, bucketName): 47 | storage_client = storage.Client() 48 | bucket = storage_client.bucket(bucketName) 49 | blob = bucket.blob(fileName) 50 | with blob.open("r") as f: 51 | results = f.readlines() 52 | if (int(results[0][0]) < openNum): 53 | # a new support ticket created 54 | return True 55 | elif (int(results[0]) == openNum and int(results[1]) < closed): 56 | #edge case where new ticket created and old ticket closed 57 | return True 58 | return False 59 | 60 | #Updates the results values in the yaml file that is passed in 61 | def updateValues(closed, openNum, fileName, bucketName): 62 | storage_client = storage.Client() 63 | bucket = storage_client.bucket(bucketName) 64 | blob = bucket.blob(fileName) 65 | with blob.open("w") as f: 66 | f.write(str(openNum) + "\n") 67 | f.write(str(closed) + "\n") 68 | 69 | #Returns the number of tickets given the project, state, and isOrganization 70 | def getNumTicket(project, state, isOrg): 71 | SERVICE_NAME = "Support API" 72 | API_VERSION = "v2beta" 73 | API_DEFINITION_URL = "https://cloudsupport.googleapis.com/$discovery/rest?version=" + API_VERSION 74 | 75 | supportApiService = googleapiclient.discovery.build( 76 | serviceName=SERVICE_NAME, 77 | version=API_VERSION, 78 | discoveryServiceUrl=API_DEFINITION_URL) 79 | 80 | if (isOrg): 81 | case_list = supportApiService.cases().list(parent="organizations/" + project, filter="state=" + state, pageSize=100).execute() 82 | else: 83 | case_list = supportApiService.cases().list(parent="projects/" + project, filter="state=" + state, pageSize=100).execute() 84 | if (len(case_list) > 0): 85 | #check if the values changed, and update the new values 86 | return len(case_list["cases"]) 87 | else: 88 | return 0 89 | return case_list 90 | 91 | #Returns list of projects under an organization 92 | def getProjectsList(): 93 | #get list of support tickets 94 | with open('organizationsList.txt') as f: 95 | projectsList = [line for line in f] 96 | with open('organizationsList.txt') as f: 97 | projectsList= [line.rstrip() for line in f] 98 | return projectsList 99 | 100 | #gets number of open and closed cases and stores it in TicketResults.txt 101 | def countForAllStates(project, organization, storageBucket, onlyProject): 102 | if (onlyProject == "False"): 103 | #notifications on for all projects 104 | numOpenTickets = 0 105 | numClosedTickets = 0 106 | projectsList = getProjectsList() 107 | #get the organization support tickets first 108 | numOpenTickets += getNumTicket(organization, "OPEN", True) 109 | numClosedTickets += getNumTicket(organization, "CLOSED", True) 110 | #get all the projects' support tickets 111 | for projectID in projectsList: 112 | numOpenTickets += getNumTicket(projectID, "OPEN", False) 113 | numClosedTickets += getNumTicket(projectID, "CLOSED", False) 114 | #check if the results are different from before 115 | shouldSendEmail = sendEmail(numClosedTickets, numOpenTickets, "TicketResults.txt", storageBucket) 116 | #update the ticket result values with the new values 117 | updateValues(numClosedTickets, numOpenTickets, "TicketResults.txt", storageBucket) 118 | return shouldSendEmail 119 | else: 120 | numOpenTickets = getNumTicket(project,"OPEN", False) 121 | numClosedTickets = getNumTicket(project, "CLOSED", False) 122 | shouldSendEmail = sendEmail(numClosedTickets, numOpenTickets, "TicketResults.txt", storageBucket) 123 | updateValues(numClosedTickets, numOpenTickets, "TicketResults.txt", storageBucket) 124 | return shouldSendEmail 125 | 126 | def main(): 127 | os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json" 128 | IDs = {'project': "", 'organization': "", 'onlyProject': ""} 129 | readConfigFile(IDs) 130 | if (IDs["onlyProject"] == "False"): 131 | #need to generate list of organizations 132 | open('organizationsList.txt', 'w').close() 133 | generateProjectIDs(IDs["organization"]) 134 | newTicketOpened = countForAllStates(IDs["project"], IDs["organization"], IDs["project"] + "-supportnotification", IDs["onlyProject"]) 135 | if (newTicketOpened): 136 | logEvent() 137 | main() 138 | --------------------------------------------------------------------------------