├── .babelrc ├── .eslintignore ├── .eslintrc ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── pull_request_template.md ├── .gitignore ├── .prettierignore ├── .prettierrc.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── __tests__ ├── App.test.ts ├── client │ ├── customMetricsTab.test.tsx │ ├── dashboard.test.tsx │ ├── drawer.test.tsx │ ├── nodesTab.test.tsx │ ├── podsTab.test.tsx │ └── visualizerTab.test.tsx └── routes.test.ts ├── client ├── App.tsx ├── Components │ ├── CustomMetricsForm.tsx │ ├── CustomMetricsTab.tsx │ ├── Dashboard.tsx │ ├── Drawer.tsx │ ├── HorizontalBarChart.tsx │ ├── LineGraph.tsx │ ├── NavInstantMetricsTable.tsx │ ├── NodeDisplay.tsx │ ├── NodesTab.tsx │ ├── PodDisplay.tsx │ ├── PodsTab.tsx │ ├── SavedCustomMetrics.tsx │ ├── SpeedometerChart.tsx │ ├── StackedBarChart.tsx │ └── VisualizerTab.tsx ├── colors.tsx ├── dark.png ├── favicon.ico ├── index.html ├── index.tsx ├── light.png └── style.css ├── jest-teardown.ts ├── jest.config.ts ├── package.json ├── server ├── controllers │ ├── clusterController.ts │ ├── customController.ts │ ├── dashboardController.ts │ ├── hierarchyController.ts │ ├── nodeController.ts │ └── podController.ts ├── routers │ ├── clusterRouter.ts │ ├── customRouter.ts │ ├── dashboardRouter.ts │ ├── hierarchyRouter.ts │ ├── nodeRouter.ts │ └── podRouter.ts └── server.ts ├── tsconfig.json ├── types.ts └── webpack.config.ts /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-typescript"] 3 | } 4 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "plugins": ["@typescript-eslint"], 5 | "extends": [ 6 | "eslint:recommended", 7 | "plugin:@typescript-eslint/eslint-recommended", 8 | "plugin:@typescript-eslint/recommended" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | 28 | - OS: [e.g. iOS] 29 | - Browser [e.g. chrome, safari] 30 | - Version [e.g. 22] 31 | 32 | **Additional context** 33 | Add any other context about the problem here. 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Related Issue 2 | 3 | - if you ran into any issues, write them here 4 | 5 | # Proposed Changes 6 | 7 | - What you changed about the application 8 | 9 | # Additional Info 10 | 11 | - any additional information or context 12 | 13 | # Checklist 14 | 15 | - [ ] Tests 16 | - [ ] Translations 17 | - [ ] Documentation 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | package-lock.json 107 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "tabWidth": 2 4 | } 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | mezhmichael@gmail.com 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to KubernOcular 2 | 3 | Thank you for your contribution! Contributions are welcome and are greatly appreciated and every little bit helps. 4 | 5 | ## Reporting Bugs 6 | 7 | All code changes happen through Github Pull Requests and we actively welcome them. To submit your pull request, follow the steps below: 8 | 9 | ## Pull Requests 10 | 11 | 1. Fork the repo and create your featured branch. 12 | 2. If you've added code that should be tested, add tests. 13 | 3. Make sure your code lints. 14 | 4. Issue that pull request! 15 | 5. Specify what you changed in details when you are doing pull request. 16 | 17 | Note: Any contributions you make will be under the MIT Software License and your submissions are understood to be under the same that covers the project. Please reach out to the team if you have any questions. 18 | 19 | ## Issues 20 | 21 | We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. 22 | 23 | ## Coding Style 24 | 25 | - 2 spaces for indentation rather than tabs 26 | - 80 character line length 27 | - Run `npm run lint` to conform to our lint rules 28 | 29 | ## License 30 | 31 | By contributing, you agree that your contributions will be licensed under KubernOcular's Mozilla Public License Version 2.0. 32 | 33 | ### References 34 | 35 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/master/CONTRIBUTING.md) 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | ## Set Up 7 | 8 | ### Prerequisites: 9 | 10 | - Install Docker Desktop on your machine: https://www.docker.com/products/docker-desktop/ 11 | - Enable Kubernetes in Docker Desktop settings 12 | - Install kubectl on your machine: 13 | - For MacOS: https://kubernetes.io/docs/tasks/tools/install-kubectl-macos/ 14 | - For Windows: https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/ 15 | - For Linux: https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/ 16 | 17 | ### Terminal Commands: 18 | 19 | 1. Clone this repository onto your local machine 20 | git clone https://github.com/oslabs-beta/KubernOcular.git 21 | 2. Install Helm using the appropriate terminal commands 22 | 23 | For MacOS/Homebrew: 24 | 25 | brew install helm 26 | 27 | For Windows/Chocolatey: 28 | 29 | choco install kubernetes-helm 30 | 31 | For Linux/Ubuntu: 32 | 33 | curl https://baltocdn.com/helm/signing.asc | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg > /dev/null 34 | 35 | sudo apt-get install apt-transport-https --yes 36 | 37 | echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list 38 | 39 | sudo apt-get install helm 40 | 41 | 3. Once Helm is properly installed, add the helm-charts repository 42 | 43 | helm repo add prometheus-community https://prometheus-community.github.io/helm-charts 44 | 45 | 4. Install the kube-prometheus-stack manifests collection with this command in your terminal 46 | 47 | helm install --set prometheus-node-exporter.hostRootFsMount.enabled=false prometheus prometheus-community/kube-prometheus-stack 48 | 49 | 5. Port-forward the Prometheus API to http://localhost:9090 50 | 51 | kubectl port-forward svc/prometheus-kube-prometheus-prometheus 9090 52 | 53 | 6. Run this command in a separate terminal in the KubernOcular directory and visit http://localhost:8080 to begin your KubernOcular experience 54 | 55 | npm run dev 56 | 57 | 7. When you are finished using KubernOcular, uninstall the prometheus monitoring stack — this should also delete the prometheus running cluster 58 | 59 | helm uninstall prometheus 60 | 61 | ## Technologies 62 | 63 | - [React](https://reactjs.org/) 64 | - [TypeScript](https://www.typescriptlang.org/) 65 | - [React Router](https://reactrouter.com/en/main) 66 | - [Material UI](https://mui.com/) 67 | - [Cytoscape](https://js.cytoscape.org/) 68 | - [Chart.js](https://www.chartjs.org/) 69 | - [Kubernetes](https://kubernetes.io/) 70 | - [Docker](https://www.docker.com/) 71 | - [Helm](https://helm.sh/) 72 | - [Node](https://nodejs.org/en/) 73 | - [Express](https://expressjs.com/) 74 | - [Kubernetes-Client](https://www.npmjs.com/package/kubernetes-client) 75 | - [Prometheus/PromQL](https://prometheus.io/) 76 | - [Jest](https://jestjs.io/) 77 | - [Supertest](https://www.npmjs.com/package/supertest) 78 | - [Puppeteer](https://pptr.dev/) 79 | - [Webpack](https://webpack.js.org/) 80 | 81 | ## The KubernOcular Team 82 | 83 | - Adam Selph: [Github](https://github.com/ARSelph) | [LinkedIn](https://www.linkedin.com/in/adam-selph-93231324a/) 84 | - Shirley Luu: [Github](https://github.com/shirley-luu) | [LinkedIn](https://www.linkedin.com/in/luu-shirley/) 85 | - Brian Preston: [Github](https://github.com/BrianJPreston) | [LinkedIn](https://www.linkedin.com/in/brian-preston-33444430/) 86 | - Evan Emenegger: [Github](https://github.com/emenegger) | [LinkedIn](https://www.linkedin.com/in/evan-emenegger/) 87 | - Michael Mezhiritskiy: [Github](https://github.com/MichaelMezhiritskiy) | [LinkedIn](https://www.linkedin.com/in/michael-mezhiritskiy-41a0aa1b4/) 88 | 89 | ## License 90 | 91 | This project is licensed under Mozilla Public License Version 2.0 - see the LICENSE.md file for details. 92 | -------------------------------------------------------------------------------- /__tests__/App.test.ts: -------------------------------------------------------------------------------- 1 | import puppeteer from 'puppeteer'; 2 | 3 | describe('App tests (end to end testing I think)', () => { 4 | let browser; 5 | let page; 6 | 7 | beforeAll(async () => { 8 | browser = await puppeteer.launch(); 9 | page = await browser.newPage(); 10 | }); 11 | 12 | afterAll(() => browser.close()); 13 | 14 | it('shows kubernocular logo on navbar', async () => { 15 | await page.goto('http://localhost:8080'); 16 | 17 | const dimensions = await page.evaluate(() => { 18 | return { 19 | width: document.documentElement.clientWidth, 20 | height: document.documentElement.clientHeight, 21 | deviceScaleFactor: window.devicePixelRatio, 22 | }; 23 | }); 24 | 25 | console.log('Dimensions:', dimensions); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /__tests__/client/customMetricsTab.test.tsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oslabs-beta/KubernOcular/80b2fa8a105d0c40634c4dc54249c8960a608a8d/__tests__/client/customMetricsTab.test.tsx -------------------------------------------------------------------------------- /__tests__/client/dashboard.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import Dashboard from '../../client/Components/Dashboard'; 4 | import userEvent from '@testing-library/user-event'; 5 | 6 | describe('Drawer', () => { 7 | beforeEach(() => { 8 | render(); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /__tests__/client/drawer.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import Drawer from '../../client/Components/Drawer'; 4 | import userEvent from '@testing-library/user-event'; 5 | 6 | describe('Drawer', () => { 7 | beforeEach(() => { 8 | render(); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /__tests__/client/nodesTab.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import NodesTab from '../../client/Components/NodesTab'; 4 | import userEvent from '@testing-library/user-event'; 5 | 6 | describe('Drawer', () => { 7 | beforeEach(() => { 8 | render(); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /__tests__/client/podsTab.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import PodsTab from '../../client/Components/PodsTab'; 4 | import userEvent from '@testing-library/user-event'; 5 | 6 | describe('Drawer', () => { 7 | beforeEach(() => { 8 | render(); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /__tests__/client/visualizerTab.test.tsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oslabs-beta/KubernOcular/80b2fa8a105d0c40634c4dc54249c8960a608a8d/__tests__/client/visualizerTab.test.tsx -------------------------------------------------------------------------------- /__tests__/routes.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | import app from '../server/server'; 3 | 4 | describe('route tests', () => { 5 | describe('/api/cluster', () => { 6 | it('/namespaces', () => { 7 | return request(app) 8 | .get('/api/cluster/namespaces') 9 | .expect('Content-Type', /application\/json/) 10 | .expect(200) 11 | .then((res) => { 12 | expect(typeof res).toBe('object'); 13 | }); 14 | }), 15 | it('/pods', () => { 16 | return request(app) 17 | .get('/api/cluster/pods?namespace=default') 18 | .expect('Content-Type', /application\/json/) 19 | .expect(200) 20 | .then((res) => { 21 | expect(typeof res).toBe('object'); 22 | }); 23 | }), 24 | it('/nodes', () => { 25 | return request(app) 26 | .get('/api/cluster/nodes') 27 | .expect('Content-Type', /application\/json/) 28 | .expect(200) 29 | .then((res) => { 30 | expect(typeof res).toBe('object'); 31 | }); 32 | }); 33 | }), 34 | describe('/api/dashboard', () => { 35 | it('/num', () => { 36 | return request(app) 37 | .get('/api/dashboard/num') 38 | .expect('Content-Type', /application\/json/) 39 | .expect(200) 40 | .then((res) => { 41 | expect(typeof res).toBe('object'); 42 | }); 43 | }), 44 | it('/general', () => { 45 | return request(app) 46 | .get('/api/dashboard/general') 47 | .expect('Content-Type', /application\/json/) 48 | .expect(200) 49 | .then((res) => { 50 | expect(typeof res).toBe('object'); 51 | }); 52 | }), 53 | it('/mem', () => { 54 | return request(app) 55 | .get('/api/dashboard/num') 56 | .expect('Content-Type', /application\/json/) 57 | .expect(200) 58 | .then((res) => { 59 | expect(typeof res).toBe('object'); 60 | }); 61 | }), 62 | it('/cpu', () => { 63 | return request(app) 64 | .get('/api/dashboard/cpu') 65 | .expect('Content-Type', /application\/json/) 66 | .expect(200) 67 | .then((res) => { 68 | expect(typeof res).toBe('object'); 69 | }); 70 | }), 71 | it('/transmit', () => { 72 | return request(app) 73 | .get('/api/dashboard/transmit') 74 | .expect('Content-Type', /application\/json/) 75 | .expect(200) 76 | .then((res) => { 77 | expect(typeof res).toBe('object'); 78 | }); 79 | }), 80 | it('/receive', () => { 81 | return request(app) 82 | .get('/api/dashboard/receive') 83 | .expect('Content-Type', /application\/json/) 84 | .expect(200) 85 | .then((res) => { 86 | expect(typeof res).toBe('object'); 87 | }); 88 | }); 89 | }); 90 | }); 91 | -------------------------------------------------------------------------------- /client/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { ThemeProvider, createTheme } from '@mui/material/styles'; 3 | import CssBaseline from '@mui/material/CssBaseline'; 4 | import Drawer from './Components/Drawer'; 5 | import './style.css'; 6 | 7 | const darkTheme = createTheme({ 8 | palette: { 9 | mode: 'dark', 10 | }, 11 | }); 12 | 13 | const App = () => { 14 | return ( 15 |
16 | 17 | 18 | 19 | 20 |
21 | ); 22 | }; 23 | 24 | export default App; 25 | -------------------------------------------------------------------------------- /client/Components/CustomMetricsForm.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { FC } from 'react'; 3 | import Stack from '@mui/material/Stack'; 4 | import Box from '@mui/material/Box'; 5 | import TextField from '@mui/material/TextField'; 6 | import InputLabel from '@mui/material/InputLabel'; 7 | import MenuItem from '@mui/material/MenuItem'; 8 | import FormControl from '@mui/material/FormControl'; 9 | import Select, { SelectChangeEvent } from '@mui/material/Select'; 10 | import Button from '@mui/material/Button'; 11 | import SendIcon from '@mui/icons-material/Send'; 12 | import TaskAltIcon from '@mui/icons-material/TaskAlt'; 13 | import ErrorIcon from '@mui/icons-material/Error'; 14 | 15 | const CustomMetricsForm: FC<{ setUpdateList: Function; updateList: number }> = ( 16 | props 17 | ) => { 18 | // preserve state of user input for custom metrics 19 | const { updateList, setUpdateList } = props; 20 | const [metricName, setMetricName] = React.useState(''); 21 | const [promQuery, setPromQuery] = React.useState(''); 22 | const [yAxisType, setYAxisType] = React.useState(''); 23 | const [scope, setScope] = React.useState(''); 24 | const [validity, setValidity] = React.useState(false); 25 | 26 | // handlers for each portion of input form 27 | const handleMetricInput = (event: React.ChangeEvent) => { 28 | setMetricName(event.target.value); 29 | }; 30 | 31 | const handleQueryInput = (event: React.ChangeEvent) => { 32 | setPromQuery(event.target.value); 33 | }; 34 | 35 | const handleYAxisSelect = (event: SelectChangeEvent) => { 36 | setYAxisType(event.target.value); 37 | }; 38 | 39 | const handleScopeSelect = (event: SelectChangeEvent) => { 40 | setScope(event.target.value); 41 | }; 42 | 43 | // upon clicking "add metric", send post request with user input data and increment saved metrics counter by 1 (for other component to recognize increase and in turn, rerender with added metric) 44 | const handleSubmit = () => { 45 | fetch('/api/custom/queries', { 46 | method: 'POST', 47 | headers: { 48 | 'Content-Type': 'application/json', 49 | }, 50 | body: JSON.stringify({ 51 | scope, 52 | query: promQuery, 53 | yAxisType, 54 | name: metricName, 55 | }), 56 | }) 57 | .then((res) => res.json()) 58 | .then((addedQuery) => { 59 | if (addedQuery) { 60 | setUpdateList(updateList + 1); 61 | } else console.log('Query was not added'); 62 | }); 63 | }; 64 | 65 | // check for validity of query upon change in prom query input field and scope select 66 | React.useEffect(() => { 67 | fetch('/api/custom/test', { 68 | method: 'POST', 69 | headers: { 70 | 'Content-Type': 'application/json', 71 | }, 72 | body: JSON.stringify({ 73 | scope: scope, 74 | query: promQuery, 75 | }), 76 | }) 77 | .then((res) => res.json()) 78 | .then((data) => setValidity(data === true ? true : false)); 79 | }, [promQuery, scope]); 80 | 81 | return ( 82 |
83 |

Create a Custom Metric

84 | 95 |
96 | 104 |
105 |
106 | {validity === true || promQuery === '' ? ( 107 | 108 | 119 |
120 | 128 |
129 |
130 | {validity && } 131 |
132 | ) : ( 133 | 134 | 145 |
146 | 156 |
157 |
158 | 159 |
160 | )} 161 | 162 | 163 | Unit Type 164 | 177 | 178 | 179 | 180 | 181 | Scope 182 | 193 | 194 | 195 | 209 |
210 | ); 211 | }; 212 | 213 | export default CustomMetricsForm; 214 | -------------------------------------------------------------------------------- /client/Components/CustomMetricsTab.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { FC } from 'react'; 3 | import Stack from '@mui/material/Stack'; 4 | import Box from '@mui/material/Box'; 5 | import CustomMetricsForm from './CustomMetricsForm'; 6 | import SavedCustomMetrics from './SavedCustomMetrics'; 7 | 8 | const CustomMetricsTab: FC = () => { 9 | // preserve state of saved metrics list (if incremented, saved custom metrics component will rerender) 10 | const [updateList, setUpdateList] = React.useState(0); 11 | 12 | return ( 13 |
14 | 15 | 28 | 32 | 33 | 45 | 46 | 47 | 48 |
49 | ); 50 | }; 51 | 52 | export default CustomMetricsTab; 53 | -------------------------------------------------------------------------------- /client/Components/Dashboard.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { FC } from 'react'; 3 | import LineGraph from './LineGraph'; 4 | import StackedBarChart from './StackedBarChart'; 5 | import HorizontalBarChart from './HorizontalBarChart'; 6 | import NavInstantMetricsTable from './NavInstantMetricsTable'; 7 | import SpeedometerChart from './SpeedometerChart'; 8 | import colors from '../colors'; 9 | 10 | const Dashboard: FC = () => { 11 | // preserve state of all custom metric graphs currently checked active for display 12 | const [customGraphs, setCustomGraphs] = React.useState([]); 13 | 14 | // upon component load, fetch custom metrics data to render graphs for cluster and push element into custom graphs state 15 | React.useEffect((): void => { 16 | const newCustomGraphs: JSX.Element[] = []; 17 | fetch('/api/custom/list?scope=cluster') 18 | .then((res) => res.json()) 19 | .then((data) => { 20 | data.forEach((metric: Record, index: number) => { 21 | if (metric.active) { 22 | const customColors: number[] = []; 23 | for (let i = 0; i < 3; i++) { 24 | customColors.push(Math.floor(Math.random() * 256)); 25 | } 26 | newCustomGraphs.push( 27 | 34 | ); 35 | } 36 | }); 37 | setCustomGraphs(newCustomGraphs); 38 | }); 39 | }, []); 40 | 41 | return ( 42 |
43 |
44 | 45 | 46 | 47 | 48 |
49 |
50 | 57 | 64 | 71 | 78 | {customGraphs} 79 |
80 |
81 | ); 82 | }; 83 | 84 | export default Dashboard; 85 | -------------------------------------------------------------------------------- /client/Components/Drawer.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { Link, Routes, Route } from 'react-router-dom'; 3 | import Dashboard from './Dashboard'; 4 | import PodsTab from './PodsTab'; 5 | import NodesTab from './NodesTab'; 6 | import CustomMetricsTab from './CustomMetricsTab'; 7 | import VisualizerTab from './VisualizerTab'; 8 | import PodDisplay from './PodDisplay'; 9 | import NodeDisplay from './NodeDisplay'; 10 | import { styled, useTheme, Theme, CSSObject } from '@mui/material/styles'; 11 | import Box from '@mui/material/Box'; 12 | import MuiDrawer from '@mui/material/Drawer'; 13 | import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar'; 14 | import Toolbar from '@mui/material/Toolbar'; 15 | import List from '@mui/material/List'; 16 | import CssBaseline from '@mui/material/CssBaseline'; 17 | import Divider from '@mui/material/Divider'; 18 | import IconButton from '@mui/material/IconButton'; 19 | import MenuIcon from '@mui/icons-material/Menu'; 20 | import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; 21 | import ChevronRightIcon from '@mui/icons-material/ChevronRight'; 22 | import ListItem from '@mui/material/ListItem'; 23 | import ListItemButton from '@mui/material/ListItemButton'; 24 | import ListItemIcon from '@mui/material/ListItemIcon'; 25 | import ListItemText from '@mui/material/ListItemText'; 26 | import AccountTreeIcon from '@mui/icons-material/AccountTree'; 27 | import DeveloperBoardIcon from '@mui/icons-material/DeveloperBoard'; 28 | import AutoAwesomeMotionIcon from '@mui/icons-material/AutoAwesomeMotion'; 29 | import VisibilityIcon from '@mui/icons-material/Visibility'; 30 | import HelpIcon from '@mui/icons-material/Help'; 31 | 32 | 33 | // renders the sidebar and gives it open/close functionality 34 | const drawerWidth = 175; 35 | 36 | const openedMixin = (theme: Theme): CSSObject => ({ 37 | width: drawerWidth, 38 | transition: theme.transitions.create('width', { 39 | easing: theme.transitions.easing.sharp, 40 | duration: theme.transitions.duration.enteringScreen, 41 | }), 42 | overflowX: 'hidden', 43 | }); 44 | 45 | const closedMixin = (theme: Theme): CSSObject => ({ 46 | transition: theme.transitions.create('width', { 47 | easing: theme.transitions.easing.sharp, 48 | duration: theme.transitions.duration.leavingScreen, 49 | }), 50 | overflowX: 'hidden', 51 | width: `calc(${theme.spacing(7)} + 1px)`, 52 | [theme.breakpoints.up('sm')]: { 53 | width: `calc(${theme.spacing(8)} + 1px)`, 54 | }, 55 | }); 56 | 57 | const DrawerHeader = styled('div')(({ theme }) => ({ 58 | display: 'flex', 59 | alignItems: 'center', 60 | justifyContent: 'flex-end', 61 | padding: theme.spacing(0, 1), 62 | // necessary for content to be below app bar 63 | ...theme.mixins.toolbar, 64 | })); 65 | 66 | interface AppBarProps extends MuiAppBarProps { 67 | open?: boolean; 68 | } 69 | 70 | const AppBar = styled(MuiAppBar, { 71 | shouldForwardProp: (prop) => prop !== 'open', 72 | })(({ theme, open }) => ({ 73 | zIndex: theme.zIndex.drawer + 1, 74 | transition: theme.transitions.create(['width', 'margin'], { 75 | easing: theme.transitions.easing.sharp, 76 | duration: theme.transitions.duration.leavingScreen, 77 | }), 78 | ...(open && { 79 | marginLeft: drawerWidth, 80 | width: `calc(100% - ${drawerWidth}px)`, 81 | transition: theme.transitions.create(['width', 'margin'], { 82 | easing: theme.transitions.easing.sharp, 83 | duration: theme.transitions.duration.enteringScreen, 84 | }), 85 | }), 86 | })); 87 | 88 | const Drawer = styled(MuiDrawer, { 89 | shouldForwardProp: (prop) => prop !== 'open', 90 | })(({ theme, open }) => ({ 91 | width: drawerWidth, 92 | flexShrink: 0, 93 | whiteSpace: 'nowrap', 94 | boxSizing: 'border-box', 95 | ...(open && { 96 | ...openedMixin(theme), 97 | '& .MuiDrawer-paper': openedMixin(theme), 98 | }), 99 | ...(!open && { 100 | ...closedMixin(theme), 101 | '& .MuiDrawer-paper': closedMixin(theme), 102 | }), 103 | })); 104 | 105 | export default function MiniDrawer() { 106 | const theme = useTheme(); 107 | const [open, setOpen] = React.useState(false); 108 | 109 | const handleDrawerOpen = () => { 110 | setOpen(true); 111 | }; 112 | 113 | const handleDrawerClose = () => { 114 | setOpen(false); 115 | }; 116 | 117 | return ( 118 | 119 | 120 | 121 | 122 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | {theme.direction === 'rtl' ? ( 146 | 147 | ) : ( 148 | 149 | )} 150 | 151 | 152 | 153 | 154 | 155 | 162 | 169 | 176 | 177 | 178 | 184 | 185 | 186 | 187 | 188 | 195 | 202 | 209 | 210 | 211 | 217 | 218 | 219 | 220 | 221 | 228 | 235 | 242 | 243 | 244 | 250 | 251 | 252 | 253 | 254 | 261 | 268 | 275 | 276 | 277 | 283 | 284 | 285 | 286 | 287 | 294 | 301 | 308 | 309 | 310 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | } /> 325 | } /> 326 | } /> 327 | } /> 328 | } /> 329 | } /> 330 | } /> 331 | 332 | 333 | 334 | ); 335 | } 336 | -------------------------------------------------------------------------------- /client/Components/HorizontalBarChart.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect } from 'react'; 2 | import { Bar } from 'react-chartjs-2'; 3 | import { useState } from 'react'; 4 | import colors from '../colors'; 5 | import ChartDataLabels from 'chartjs-plugin-datalabels'; 6 | import { 7 | Chart as ChartJS, 8 | CategoryScale, 9 | LinearScale, 10 | BarElement, 11 | Title, 12 | Tooltip, 13 | Legend, 14 | ChartOptions, 15 | ChartData, 16 | } from 'chart.js'; 17 | 18 | ChartJS.register( 19 | CategoryScale, 20 | LinearScale, 21 | BarElement, 22 | Title, 23 | Tooltip, 24 | Legend, 25 | ChartDataLabels 26 | ); 27 | 28 | type MetricProps = { 29 | label: string; 30 | }; 31 | 32 | const initialData: ChartData<'bar'> = { 33 | datasets: [], 34 | }; 35 | 36 | const labels = ['CPU Usage %']; 37 | 38 | const HorizontalBarChart: FC = () => { 39 | const [data, setData] = useState(initialData); 40 | 41 | const options: ChartOptions<'bar'> = { 42 | responsive: true, 43 | maintainAspectRatio: false, 44 | // aspectRatio: 45 | indexAxis: 'y', 46 | elements: { 47 | bar: { 48 | borderWidth: 2, 49 | }, 50 | }, 51 | scales: { 52 | x: { 53 | beginAtZero: true, 54 | max: 100, 55 | }, 56 | y: { 57 | display: false, 58 | }, 59 | }, 60 | plugins: { 61 | datalabels: { 62 | color: '#cee2fd', 63 | font: { 64 | weight: 'bold', 65 | }, 66 | formatter: Math.round, 67 | }, 68 | legend: { 69 | display: false, 70 | }, 71 | title: { 72 | display: true, 73 | text: 'CPU Usage %', 74 | color: '#e1eeff', 75 | }, 76 | }, 77 | }; 78 | 79 | // queries the cpu usage and displays info as a bar chart 80 | useEffect(() => { 81 | fetch('../api/dashboard/cpu') 82 | .then((res) => res.json()) 83 | .then((data) => { 84 | const usefulData = 85 | data.data.result[0].values[data.data.result[0].values.length - 1]; 86 | const chartData = Number(usefulData[1]); 87 | const backgroundColor = 88 | chartData >= 90 ? colors.translucent.red : colors.translucent.green; 89 | 90 | const newData: ChartData<'bar'> = { 91 | labels: labels, 92 | datasets: [ 93 | { 94 | label: 'Dataset 1', 95 | data: [chartData], 96 | borderColor: backgroundColor, 97 | backgroundColor: backgroundColor, 98 | datalabels: { 99 | align: 'center', 100 | anchor: 'center', 101 | }, 102 | }, 103 | ], 104 | }; 105 | setData(newData); 106 | }) 107 | .catch((err) => console.log(err)); 108 | }, []); 109 | 110 | return ( 111 |
112 | 113 |
114 | ); 115 | }; 116 | 117 | export default HorizontalBarChart; 118 | -------------------------------------------------------------------------------- /client/Components/LineGraph.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { FC, useState } from 'react'; 3 | import { Line } from 'react-chartjs-2'; 4 | import WarningAmberIcon from '@mui/icons-material/WarningAmber'; 5 | import CircularProgress from '@mui/material/CircularProgress'; 6 | import { 7 | Chart as ChartJS, 8 | CategoryScale, 9 | LinearScale, 10 | PointElement, 11 | LineElement, 12 | Title, 13 | Tooltip, 14 | Legend, 15 | ChartOptions, 16 | ChartData, 17 | } from 'chart.js'; 18 | 19 | ChartJS.register( 20 | CategoryScale, 21 | LinearScale, 22 | PointElement, 23 | LineElement, 24 | Title, 25 | Tooltip, 26 | Legend 27 | ); 28 | 29 | type MetricProps = { 30 | query: string; 31 | label: string; 32 | backgroundColor: string; 33 | borderColor: string; 34 | yAxisType: string; 35 | }; 36 | 37 | const initialData: ChartData<'line'> = { 38 | datasets: [], 39 | }; 40 | 41 | const LineGraph: FC = (props) => { 42 | const [chartLoaded, setChartLoaded] = useState(false); 43 | const [data, setData] = useState(initialData); 44 | const [loadError, setLoadError] = useState(false); 45 | 46 | const options: ChartOptions<'line'> = { 47 | animation: { 48 | easing: 'easeInCubic', 49 | duration: 1200, 50 | }, 51 | responsive: true, 52 | interaction: { 53 | intersect: false, 54 | }, 55 | plugins: { 56 | legend: { 57 | position: 'top', 58 | }, 59 | title: { 60 | display: true, 61 | text: '', 62 | }, 63 | filler: { 64 | drawTime: 'beforeDatasetsDraw', 65 | propagate: true, 66 | }, 67 | // displays data labels inside the chart 68 | datalabels: { 69 | display: false, 70 | }, 71 | }, 72 | scales: { 73 | // <-- ScaleChartOptions 74 | y: { 75 | // <-- ScaleOptionsByType 76 | display: true, // <-- any options within CartesianScaleTypeRegistry 77 | axis: 'y', 78 | title: { 79 | display: true, 80 | text: props.yAxisType, 81 | }, 82 | }, 83 | x: { 84 | // <-- ScaleOptionsByType 85 | display: true, // <-- any options within CartesianScaleTypeRegistry 86 | axis: 'y', 87 | title: { 88 | display: true, 89 | text: 'Time', 90 | }, 91 | }, 92 | }, 93 | }; 94 | 95 | // on load, the component accesses the passed-in query and displays the result as a line graph 96 | useEffect(() => { 97 | fetch(props.query) 98 | .then((res) => res.json()) 99 | .then((data) => { 100 | // removes unnecessary data 101 | const usefulData = data.data.result[0].values; 102 | console.log('usefulData', usefulData); 103 | // the following commented code will display a date when the day changes - this is turned off for the production build 104 | // let displayDate = true; 105 | // let prevDate = ''; 106 | // maps the xAxis label 107 | const xAxisLabels = usefulData.map((value: [number, string]) => { 108 | // logic for converting timestamp to human-readable time 109 | const currentDate = new Date(value[0] * 1000); 110 | let timeString = currentDate.toLocaleString('en-GB'); 111 | const iOfComma = timeString.indexOf(',') + 1; 112 | timeString = timeString.slice(iOfComma).trim(); 113 | // displayDate = false; 114 | return timeString; 115 | }); 116 | let yAxisValues: number[] = []; 117 | switch (props.yAxisType) { 118 | case 'gigabytes': 119 | yAxisValues = usefulData.map( 120 | (value: [number, string]) => Number(value[1]) / 1000000000 121 | ); 122 | break; 123 | case 'kilobytes': 124 | yAxisValues = usefulData.map( 125 | (value: [number, string]) => Number(value[1]) / 1000000 126 | ); 127 | break; 128 | default: 129 | yAxisValues = usefulData.map((value: [number, string]) => 130 | Number(value[1]) 131 | ); 132 | } 133 | 134 | const newData: ChartData<'line'> = { 135 | labels: xAxisLabels, 136 | datasets: [ 137 | { 138 | label: props.label, 139 | data: yAxisValues, 140 | backgroundColor: props.backgroundColor, 141 | borderColor: props.borderColor, 142 | borderWidth: 1.5, 143 | pointRadius: 1, 144 | tension: 0.3, 145 | pointBorderWidth: 1, 146 | pointHoverRadius: 4, 147 | fill: true, 148 | capBezierPoints: true, 149 | }, 150 | ], 151 | }; 152 | setData(newData); 153 | setChartLoaded(true); 154 | }) 155 | .catch((err) => { 156 | console.log(err); 157 | setLoadError(true); 158 | }); 159 | }, []); 160 | 161 | if (loadError) { 162 | return ( 163 |
164 | 165 |
Error loading graph
166 |
167 | This could be because your server API or Prometheus API is not active. Check our documentation for instructions on how to set up Prometheus. 168 |
169 |
170 | ); 171 | } else if (!chartLoaded) { 172 | return ( 173 |
174 | 175 |
176 | ); 177 | } else { 178 | return ( 179 |
180 | 181 |
182 | ); 183 | } 184 | }; 185 | 186 | export default LineGraph; 187 | -------------------------------------------------------------------------------- /client/Components/NavInstantMetricsTable.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect } from 'react'; 2 | import { useState } from 'react'; 3 | 4 | type MetricProps = { 5 | label: string; 6 | }; 7 | 8 | const NavInstantMetricsTable: FC = (props) => { 9 | const [metricDivs, setMetricDivs] = useState([]); 10 | 11 | useEffect(() => { 12 | fetch('../api/dashboard/num') 13 | .then((res) => res.json()) 14 | .then((data) => { 15 | const newMetricDivs: JSX.Element[] = []; 16 | for (const prop in data) { 17 | newMetricDivs.push( 18 |
19 |
{prop}
20 |
{data[prop]}
21 |
22 | ); 23 | } 24 | setMetricDivs(newMetricDivs); 25 | }); 26 | }, []); 27 | 28 | return ( 29 | 32 | ); 33 | }; 34 | 35 | export default NavInstantMetricsTable; 36 | -------------------------------------------------------------------------------- /client/Components/NodeDisplay.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { FC } from 'react'; 3 | import LineGraph from './LineGraph'; 4 | import { useNavigate, useSearchParams } from 'react-router-dom'; 5 | import Button from '@mui/material/Button'; 6 | import ArrowBackIcon from '@mui/icons-material/ArrowBack'; 7 | 8 | const NodeDisplay: FC = () => { 9 | const [searchParams, setSearchParams] = useSearchParams(); 10 | const nodeIP = searchParams.get('nodeip'); 11 | const nodeName = searchParams.get('name'); 12 | const navigate = useNavigate(); 13 | const [customGraphs, setCustomGraphs] = React.useState([]); 14 | 15 | // upon component load, fetch custom metrics data to render graphs for nodes and push element into custom graphs state 16 | React.useEffect((): void => { 17 | const newCustomGraphs: JSX.Element[] = []; 18 | fetch('/api/custom/list?scope=node') 19 | .then((res) => res.json()) 20 | .then((data) => { 21 | data.forEach((metric: any, index: number) => { 22 | if (metric.active) { 23 | const customColors: number[] = []; 24 | for (let i = 0; i < 3; i++) { 25 | customColors.push(Math.floor(Math.random() * 256)); 26 | } 27 | newCustomGraphs.push( 28 | 35 | ); 36 | } 37 | }); 38 | setCustomGraphs(newCustomGraphs); 39 | }); 40 | }, []); 41 | 42 | return ( 43 |
44 |
50 | 58 |
59 |
60 | 67 | 74 | {customGraphs} 75 |
76 |
77 | ); 78 | }; 79 | 80 | export default NodeDisplay; 81 | -------------------------------------------------------------------------------- /client/Components/NodesTab.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { useNavigate } from 'react-router-dom'; 3 | import axios from 'axios'; 4 | import Box from '@mui/material/Box'; 5 | import Table from '@mui/material/Table'; 6 | import TableBody from '@mui/material/TableBody'; 7 | import TableCell from '@mui/material/TableCell'; 8 | import TableContainer from '@mui/material/TableContainer'; 9 | import TableHead from '@mui/material/TableHead'; 10 | import TablePagination from '@mui/material/TablePagination'; 11 | import TableRow from '@mui/material/TableRow'; 12 | import TableSortLabel from '@mui/material/TableSortLabel'; 13 | import Toolbar from '@mui/material/Toolbar'; 14 | import Typography from '@mui/material/Typography'; 15 | import Paper from '@mui/material/Paper'; 16 | import FormControlLabel from '@mui/material/FormControlLabel'; 17 | import Switch from '@mui/material/Switch'; 18 | import { visuallyHidden } from '@mui/utils'; 19 | 20 | interface Data { 21 | name: string; 22 | transmit: number; 23 | receive: number; 24 | } 25 | 26 | function createData(name: string, transmit: number, receive: number): Data { 27 | return { 28 | name, 29 | transmit, 30 | receive, 31 | }; 32 | } 33 | 34 | function descendingComparator(a: T, b: T, orderBy: keyof T) { 35 | if (b[orderBy] < a[orderBy]) { 36 | return -1; 37 | } 38 | if (b[orderBy] > a[orderBy]) { 39 | return 1; 40 | } 41 | return 0; 42 | } 43 | 44 | type Order = 'asc' | 'desc'; 45 | 46 | function getComparator( 47 | order: Order, 48 | orderBy: Key 49 | ): ( 50 | a: { [key in Key]: number | string }, 51 | b: { [key in Key]: number | string } 52 | ) => number { 53 | return order === 'desc' 54 | ? (a, b) => descendingComparator(a, b, orderBy) 55 | : (a, b) => -descendingComparator(a, b, orderBy); 56 | } 57 | 58 | // This method is created for cross-browser compatibility, if you don't 59 | // need to support IE11, you can use Array.prototype.sort() directly 60 | function stableSort( 61 | array: readonly T[], 62 | comparator: (a: T, b: T) => number 63 | ) { 64 | const stabilizedThis = array.map((el, index) => [el, index] as [T, number]); 65 | stabilizedThis.sort((a, b) => { 66 | const order = comparator(a[0], b[0]); 67 | if (order !== 0) { 68 | return order; 69 | } 70 | return a[1] - b[1]; 71 | }); 72 | return stabilizedThis.map((el) => el[0]); 73 | } 74 | 75 | interface HeadCell { 76 | disablePadding: boolean; 77 | id: keyof Data; 78 | label: string; 79 | numeric: boolean; 80 | } 81 | 82 | const headCells: readonly HeadCell[] = [ 83 | { 84 | id: 'name', 85 | numeric: false, 86 | disablePadding: true, 87 | label: 'Node Name', 88 | }, 89 | { 90 | id: 'transmit', 91 | numeric: true, 92 | disablePadding: false, 93 | label: 'Transmit Bytes', 94 | }, 95 | { 96 | id: 'receive', 97 | numeric: true, 98 | disablePadding: false, 99 | label: 'Receive Bytes', 100 | }, 101 | ]; 102 | 103 | interface EnhancedTableProps { 104 | onRequestSort: ( 105 | event: React.MouseEvent, 106 | property: keyof Data 107 | ) => void; 108 | order: Order; 109 | orderBy: string; 110 | rowCount: number; 111 | } 112 | 113 | function EnhancedTableHead(props: EnhancedTableProps) { 114 | const { order, orderBy, onRequestSort } = props; 115 | const createSortHandler = 116 | (property: keyof Data) => (event: React.MouseEvent) => { 117 | onRequestSort(event, property); 118 | }; 119 | 120 | return ( 121 | 122 | 123 | 124 | {headCells.map((headCell) => ( 125 | 131 | 136 | {headCell.label} 137 | {orderBy === headCell.id ? ( 138 | 139 | {order === 'desc' ? 'sorted descending' : 'sorted ascending'} 140 | 141 | ) : null} 142 | 143 | 144 | ))} 145 | 146 | 147 | ); 148 | } 149 | 150 | const EnhancedTableToolbar = () => { 151 | return ( 152 | 158 | 164 | Nodes 165 | 166 | 167 | ); 168 | }; 169 | 170 | export default function EnhancedTable() { 171 | const [order, setOrder] = React.useState('asc'); 172 | const [orderBy, setOrderBy] = React.useState('name'); 173 | const [page, setPage] = React.useState(0); 174 | const [dense, setDense] = React.useState(false); 175 | const [rowsPerPage, setRowsPerPage] = React.useState(10); 176 | const [rows, setRows] = React.useState([createData('[empty]', 0, 0)]); 177 | const defaultNameToIP: StringMap = {}; 178 | const [nameToIP, setNameToIP] = React.useState(defaultNameToIP); 179 | 180 | type StringMap = { 181 | [index: string]: string; 182 | }; 183 | 184 | // upon component load, fetch list of all nodes along with instant metrics for each (transmit and receive bytes) 185 | React.useEffect((): void => { 186 | const fetchNodes = async () => { 187 | const allNodes = await axios.get('/api/cluster/nodes'); 188 | const instantMetrics = await axios.get('/api/node/instant'); 189 | const newRows: any = {}; 190 | const newNameToIP: StringMap = { ...nameToIP }; 191 | for (let i = 0; i < allNodes.data.length; i++) { 192 | const nodeName: string = allNodes.data[i].name; 193 | const nodeIP: string = allNodes.data[i].ip; 194 | newNameToIP[nodeName] = nodeIP; 195 | if (!newRows[nodeName]) 196 | newRows[nodeName] = createData( 197 | nodeName, 198 | Math.round(Number(instantMetrics.data[nodeIP].transmit)), 199 | Math.round(Number(instantMetrics.data[nodeIP].receive)) 200 | ); 201 | } 202 | setRows(Object.values(newRows)); 203 | setNameToIP(newNameToIP); 204 | }; 205 | fetchNodes(); 206 | }, []); 207 | 208 | const handleRequestSort = ( 209 | event: React.MouseEvent, 210 | property: keyof Data 211 | ) => { 212 | const isAsc = orderBy === property && order === 'asc'; 213 | setOrder(isAsc ? 'desc' : 'asc'); 214 | setOrderBy(property); 215 | }; 216 | 217 | const navigate = useNavigate(); 218 | const handleClick = (event: React.MouseEvent, name: string) => { 219 | navigate(`../nodedisplay/?nodeip=${nameToIP[name]}&name=${name}`); 220 | }; 221 | 222 | const handleChangePage = (event: unknown, newPage: number) => { 223 | setPage(newPage); 224 | }; 225 | 226 | const handleChangeRowsPerPage = ( 227 | event: React.ChangeEvent 228 | ) => { 229 | setRowsPerPage(parseInt(event.target.value, 10)); 230 | setPage(0); 231 | }; 232 | 233 | const handleChangeDense = (event: React.ChangeEvent) => { 234 | setDense(event.target.checked); 235 | }; 236 | 237 | // Avoid a layout jump when reaching the last page with empty rows. 238 | const emptyRows = 239 | page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0; 240 | 241 | return ( 242 |
243 | 244 | 245 | 246 | 247 | 252 | 258 | 259 | {/* if you don't need to support IE11, you can replace the `stableSort` call with: 260 | rows.slice().sort(getComparator(order, orderBy)) */} 261 | {stableSort(rows, getComparator(order, orderBy)) 262 | .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) 263 | .map((row, index) => { 264 | const labelId = `enhanced-table-checkbox-${index}`; 265 | 266 | return ( 267 | handleClick(event, row.name)} 270 | role="checkbox" 271 | tabIndex={-1} 272 | key={row.name} 273 | > 274 | 275 | 281 | {row.name} 282 | 283 | {row.transmit} 284 | {row.receive} 285 | 286 | ); 287 | })} 288 | {emptyRows > 0 && ( 289 | 294 | 295 | 296 | )} 297 | 298 |
299 |
300 | 309 |
310 | 317 | } 318 | label="compact display" 319 | sx={{ ml: 3 }} 320 | /> 321 |
322 |
323 | ); 324 | } 325 | -------------------------------------------------------------------------------- /client/Components/PodDisplay.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { FC } from 'react'; 3 | import LineGraph from './LineGraph'; 4 | import { useNavigate, useSearchParams } from 'react-router-dom'; 5 | import Button from '@mui/material/Button'; 6 | import ArrowBackIcon from '@mui/icons-material/ArrowBack'; 7 | 8 | const PodDisplay: FC = () => { 9 | const [searchParams, setSearchParams] = useSearchParams(); 10 | const pod = searchParams.get('podname'); 11 | const navigate = useNavigate(); 12 | const [customGraphs, setCustomGraphs] = React.useState([]); 13 | 14 | // upon component load, fetch custom metrics data to render graphs for pods and push element into custom graphs state 15 | React.useEffect((): void => { 16 | const newCustomGraphs: JSX.Element[] = []; 17 | fetch('/api/custom/list?scope=pod') 18 | .then((res) => res.json()) 19 | .then((data) => { 20 | data.forEach((metric: any, index: number) => { 21 | if (metric.active) { 22 | const customColors: number[] = []; 23 | for (let i = 0; i < 3; i++) { 24 | customColors.push(Math.floor(Math.random() * 256)); 25 | } 26 | newCustomGraphs.push( 27 | 34 | ); 35 | } 36 | }); 37 | setCustomGraphs(newCustomGraphs); 38 | }); 39 | }, []); 40 | 41 | return ( 42 |
43 |
49 | 57 |
58 |
59 | 66 | 73 | {customGraphs} 74 |
75 |
76 | ); 77 | }; 78 | 79 | export default PodDisplay; 80 | -------------------------------------------------------------------------------- /client/Components/PodsTab.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { useNavigate } from 'react-router-dom'; 3 | import axios from 'axios'; 4 | import Box from '@mui/material/Box'; 5 | import Table from '@mui/material/Table'; 6 | import TableBody from '@mui/material/TableBody'; 7 | import TableCell from '@mui/material/TableCell'; 8 | import TableContainer from '@mui/material/TableContainer'; 9 | import TableHead from '@mui/material/TableHead'; 10 | import TablePagination from '@mui/material/TablePagination'; 11 | import TableRow from '@mui/material/TableRow'; 12 | import TableSortLabel from '@mui/material/TableSortLabel'; 13 | import Toolbar from '@mui/material/Toolbar'; 14 | import Typography from '@mui/material/Typography'; 15 | import Paper from '@mui/material/Paper'; 16 | import FormControlLabel from '@mui/material/FormControlLabel'; 17 | import Switch from '@mui/material/Switch'; 18 | import { visuallyHidden } from '@mui/utils'; 19 | import Button from '@mui/material/Button'; 20 | import Menu from '@mui/material/Menu'; 21 | import MenuItem from '@mui/material/MenuItem'; 22 | 23 | function NamespaceDropDown(props: { 24 | setRows: React.Dispatch>; 25 | }) { 26 | const [anchorEl, setAnchorEl] = React.useState(null); 27 | const [namespaces, setNamespaces] = React.useState([]); 28 | const [selectedNamespace, setSelectedNamespace] = React.useState(''); 29 | 30 | const open = Boolean(anchorEl); 31 | 32 | const handleClick = (event: React.MouseEvent) => { 33 | setAnchorEl(event.currentTarget); 34 | }; 35 | 36 | const handleClose = ( 37 | event: React.MouseEvent, 38 | namespace: string 39 | ): void => { 40 | setAnchorEl(null); 41 | if (namespace !== 'backdropClick') setSelectedNamespace(namespace); 42 | }; 43 | 44 | // upon component load, fetch list of all namespaces in order to render pods table by namespace 45 | React.useEffect((): void => { 46 | const namespaceArr: string[] = []; 47 | const fetchNamespaces = async () => { 48 | const allNamespaces = await axios.get('../api/cluster/namespaces'); 49 | const tempArray: JSX.Element[] = []; 50 | for (const namespace of allNamespaces.data) { 51 | namespaceArr.push(namespace); 52 | tempArray.push( 53 | handleClose(event, namespace)}> 54 | {namespace} 55 | 56 | ); 57 | } 58 | setNamespaces(tempArray); 59 | }; 60 | fetchNamespaces().then(() => setSelectedNamespace(namespaceArr[0])); 61 | }, []); 62 | 63 | // new selection of namespace, fetch new list of pods based on namespace selection 64 | React.useEffect((): void => { 65 | const fetchPods = async () => { 66 | const allPodData = await axios.get( 67 | `/api/pod/instant?namespace=${selectedNamespace}` 68 | ); 69 | const cpuData = allPodData.data.cpu; 70 | const memData = allPodData.data.mem; 71 | const newRows: any = {}; 72 | for (let i = 0; i < cpuData.length; i++) { 73 | const podName = cpuData[i].metric.pod; 74 | const cpuMetric = cpuData[i].value[1]; 75 | const memMetric = memData[i].value[1]; 76 | if (!newRows[podName]) 77 | newRows[podName] = createData(podName, cpuMetric, memMetric); 78 | } 79 | props.setRows(Object.values(newRows)); 80 | }; 81 | fetchPods(); 82 | }, [selectedNamespace]); 83 | 84 | return ( 85 |
86 | 98 | 107 | {namespaces} 108 | 109 |
110 | ); 111 | } 112 | 113 | interface Data { 114 | cpu: number; 115 | mem: number; 116 | name: string; 117 | } 118 | 119 | function createData(name: string, cpu: number, mem: number): Data { 120 | return { 121 | name, 122 | cpu, 123 | mem, 124 | }; 125 | } 126 | 127 | function descendingComparator(a: T, b: T, orderBy: keyof T) { 128 | if (b[orderBy] < a[orderBy]) { 129 | return -1; 130 | } 131 | if (b[orderBy] > a[orderBy]) { 132 | return 1; 133 | } 134 | return 0; 135 | } 136 | 137 | type Order = 'asc' | 'desc'; 138 | 139 | function getComparator( 140 | order: Order, 141 | orderBy: Key 142 | ): ( 143 | a: { [key in Key]: number | string }, 144 | b: { [key in Key]: number | string } 145 | ) => number { 146 | return order === 'desc' 147 | ? (a, b) => descendingComparator(a, b, orderBy) 148 | : (a, b) => -descendingComparator(a, b, orderBy); 149 | } 150 | 151 | // This method is created for cross-browser compatibility, if you don't 152 | // need to support IE11, you can use Array.prototype.sort() directly 153 | function stableSort( 154 | array: readonly T[], 155 | comparator: (a: T, b: T) => number 156 | ) { 157 | const stabilizedThis = array.map((el, index) => [el, index] as [T, number]); 158 | stabilizedThis.sort((a, b) => { 159 | const order = comparator(a[0], b[0]); 160 | if (order !== 0) { 161 | return order; 162 | } 163 | return a[1] - b[1]; 164 | }); 165 | return stabilizedThis.map((el) => el[0]); 166 | } 167 | 168 | interface HeadCell { 169 | disablePadding: boolean; 170 | id: keyof Data; 171 | label: string; 172 | numeric: boolean; 173 | } 174 | 175 | const headCells: readonly HeadCell[] = [ 176 | { 177 | id: 'name', 178 | numeric: false, 179 | disablePadding: true, 180 | label: 'Pod Name', 181 | }, 182 | { 183 | id: 'cpu', 184 | numeric: true, 185 | disablePadding: false, 186 | label: 'CPU Usage', 187 | }, 188 | { 189 | id: 'mem', 190 | numeric: true, 191 | disablePadding: false, 192 | label: 'Memory Usage', 193 | }, 194 | ]; 195 | 196 | interface EnhancedTableProps { 197 | onRequestSort: ( 198 | event: React.MouseEvent, 199 | property: keyof Data 200 | ) => void; 201 | order: Order; 202 | orderBy: string; 203 | rowCount: number; 204 | } 205 | 206 | function EnhancedTableHead(props: EnhancedTableProps) { 207 | const { order, orderBy, onRequestSort } = props; 208 | const createSortHandler = 209 | (property: keyof Data) => (event: React.MouseEvent) => { 210 | onRequestSort(event, property); 211 | }; 212 | 213 | return ( 214 | 215 | 216 | 217 | {headCells.map((headCell) => ( 218 | 224 | 229 | {headCell.label} 230 | {orderBy === headCell.id ? ( 231 | 232 | {order === 'desc' ? 'sorted descending' : 'sorted ascending'} 233 | 234 | ) : null} 235 | 236 | 237 | ))} 238 | 239 | 240 | ); 241 | } 242 | 243 | const EnhancedTableToolbar = () => { 244 | return ( 245 | 251 | 257 | Pods 258 | 259 | 260 | ); 261 | }; 262 | 263 | export default function EnhancedTable() { 264 | const [order, setOrder] = React.useState('asc'); 265 | const [orderBy, setOrderBy] = React.useState('cpu'); 266 | const [page, setPage] = React.useState(0); 267 | const [dense, setDense] = React.useState(false); 268 | const [rowsPerPage, setRowsPerPage] = React.useState(10); 269 | const [rows, setRows] = React.useState([createData('[empty]', 0, 0)]); 270 | 271 | const handleRequestSort = ( 272 | event: React.MouseEvent, 273 | property: keyof Data 274 | ) => { 275 | const isAsc = orderBy === property && order === 'asc'; 276 | setOrder(isAsc ? 'desc' : 'asc'); 277 | setOrderBy(property); 278 | }; 279 | 280 | const navigate = useNavigate(); 281 | const handleClick = (event: React.MouseEvent, name: string) => { 282 | navigate(`../poddisplay/?podname=${name}`); 283 | }; 284 | 285 | const handleChangePage = (event: unknown, newPage: number) => { 286 | setPage(newPage); 287 | }; 288 | 289 | const handleChangeRowsPerPage = ( 290 | event: React.ChangeEvent 291 | ) => { 292 | setRowsPerPage(parseInt(event.target.value, 10)); 293 | setPage(0); 294 | }; 295 | 296 | const handleChangeDense = (event: React.ChangeEvent) => { 297 | setDense(event.target.checked); 298 | }; 299 | 300 | // Avoid a layout jump when reaching the last page with empty rows. 301 | const emptyRows = 302 | page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0; 303 | 304 | return ( 305 |
306 | 307 | 308 | 309 |
317 | 318 |
319 | 320 | 325 | 331 | 332 | {/* if you don't need to support IE11, you can replace the `stableSort` call with: 333 | rows.slice().sort(getComparator(order, orderBy)) */} 334 | {stableSort(rows, getComparator(order, orderBy)) 335 | .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) 336 | .map((row, index) => { 337 | const labelId = `enhanced-table-checkbox-${index}`; 338 | 339 | return ( 340 | handleClick(event, row.name)} 343 | role="checkbox" 344 | tabIndex={-1} 345 | key={row.name} 346 | > 347 | 348 | 354 | {row.name} 355 | 356 | {row.cpu} 357 | {row.mem} 358 | 359 | ); 360 | })} 361 | {emptyRows > 0 && ( 362 | 367 | 368 | 369 | )} 370 | 371 |
372 |
373 | 382 |
383 | 390 | } 391 | label="compact display" 392 | sx={{ ml: 3 }} 393 | /> 394 |
395 |
396 | ); 397 | } 398 | -------------------------------------------------------------------------------- /client/Components/SavedCustomMetrics.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { FC, useState, useEffect } from 'react'; 3 | import Box from '@mui/material/Box'; 4 | import InputLabel from '@mui/material/InputLabel'; 5 | import MenuItem from '@mui/material/MenuItem'; 6 | import FormControl from '@mui/material/FormControl'; 7 | import Select, { SelectChangeEvent } from '@mui/material/Select'; 8 | import List from '@mui/material/List'; 9 | import ListItem from '@mui/material/ListItem'; 10 | import ListItemButton from '@mui/material/ListItemButton'; 11 | import ListItemIcon from '@mui/material/ListItemIcon'; 12 | import ListItemText from '@mui/material/ListItemText'; 13 | import Checkbox from '@mui/material/Checkbox'; 14 | import IconButton from '@mui/material/IconButton'; 15 | import HighlightOffIcon from '@mui/icons-material/HighlightOff'; 16 | 17 | /* handles logic for getting the current saved custom metrics, 18 | as well as toggling their active state and deleting them */ 19 | const SavedCustomMetrics: FC<{ updateList: number }> = (props) => { 20 | const { updateList } = props; 21 | const defaultMetricNames: string[] = []; 22 | const defaultActive: number[] = []; 23 | const [scope, setScope] = useState('cluster'); 24 | const [metricNames, setMetricNames] = useState(defaultMetricNames); 25 | const [active, setActive] = useState(defaultActive); 26 | 27 | const handleBoxChange = (event: SelectChangeEvent) => { 28 | setScope(event.target.value as string); 29 | }; 30 | 31 | const resetMetricDisplay = () => { 32 | fetch(`/api/custom/list?scope=${scope}`) 33 | .then((res) => res.json()) 34 | .then((data) => { 35 | const newMetricNames: string[] = []; 36 | const newActive: number[] = []; 37 | for (let i = 0; i < data.length; i++) { 38 | newMetricNames.push(data[i].name); 39 | if (data[i].active) newActive.push(i); 40 | } 41 | setMetricNames(newMetricNames); 42 | setActive(newActive); 43 | }); 44 | }; 45 | 46 | useEffect(resetMetricDisplay, [scope, updateList]); 47 | 48 | const handleDelete = async (index: number) => { 49 | const didDelete = await fetch('/api/custom/queries', { 50 | method: 'DELETE', 51 | headers: { 52 | 'Content-Type': 'application/json', 53 | }, 54 | body: JSON.stringify({ scope, id: index }), 55 | }); 56 | if (didDelete.status === 200) { 57 | resetMetricDisplay(); 58 | } 59 | }; 60 | 61 | const handleChange = async (index: number) => { 62 | const didChangeActive = await fetch('/api/custom/active', { 63 | method: 'POST', 64 | headers: { 65 | 'Content-Type': 'application/json', 66 | }, 67 | body: JSON.stringify({ 68 | scope, 69 | id: index, 70 | active: !active.includes(index), 71 | }), 72 | }); 73 | 74 | if (didChangeActive.status === 200) { 75 | resetMetricDisplay(); 76 | } 77 | }; 78 | 79 | const [checked, setChecked] = React.useState([0]); 80 | 81 | return ( 82 |
83 |

Saved Metrics

84 | 85 | 86 | Scope 87 | 98 | 99 | 100 | 109 | {metricNames.map((name, index) => { 110 | const labelId = `checkbox-list-label-${index}`; 111 | return ( 112 | handleDelete(index)} 119 | > 120 | 121 | 122 | } 123 | disablePadding 124 | > 125 | handleChange(index)} 128 | dense 129 | > 130 | 131 | 140 | 141 | 142 | 143 | 144 | ); 145 | })} 146 | 147 |
148 | ); 149 | }; 150 | 151 | export default SavedCustomMetrics; 152 | -------------------------------------------------------------------------------- /client/Components/SpeedometerChart.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC } from 'react'; 2 | import { useState, useEffect } from 'react'; 3 | import { Doughnut } from 'react-chartjs-2'; 4 | import colors from '../colors'; 5 | import { 6 | Chart as ChartJS, 7 | CategoryScale, 8 | LinearScale, 9 | PointElement, 10 | LineElement, 11 | Title, 12 | Tooltip, 13 | Legend, 14 | ChartOptions, 15 | ChartData, 16 | ArcElement, 17 | } from 'chart.js'; 18 | 19 | ChartJS.register( 20 | CategoryScale, 21 | LinearScale, 22 | PointElement, 23 | LineElement, 24 | Title, 25 | Tooltip, 26 | Legend, 27 | ArcElement 28 | ); 29 | 30 | type MetricProps = { 31 | label: string; 32 | }; 33 | 34 | interface FetchedData { 35 | heapSizeUsed: number; 36 | heapSizeBytes: number; 37 | difference: number; 38 | percentage: number; 39 | } 40 | const dataArg: FetchedData = { 41 | heapSizeUsed: 0, 42 | heapSizeBytes: 0, 43 | difference: 0, 44 | percentage: 0, 45 | }; 46 | 47 | const SpeedometerChart: FC = () => { 48 | const [chartData, setChartData] = useState(dataArg); 49 | 50 | useEffect((): void => { 51 | fetch('/api/dashboard/general') 52 | .then((res) => res.json()) 53 | .then((data) => { 54 | const fetchedData: FetchedData = { 55 | heapSizeUsed: Number((data.heapSizeUsed / 1000000).toFixed(2)), 56 | heapSizeBytes: Number((data.heapSizeBytes / 1000000).toFixed(2)), 57 | difference: Number( 58 | ( 59 | data.heapSizeBytes / 1000000 - 60 | data.heapSizeUsed / 1000000 61 | ).toFixed(2) 62 | ), 63 | percentage: data.heapSizeUsed / data.heapSizeByes, 64 | // color: this.percentage > .9 ? 'rgba(255, 99, 132, 0.2)' : 'rgba(75, 192, 192, 0.2)', 65 | }; 66 | setChartData(fetchedData); 67 | }) 68 | .catch((err) => console.log(err)); 69 | }, []); 70 | 71 | const options: ChartOptions<'doughnut'> = { 72 | animation: { 73 | easing: 'easeInCubic', 74 | duration: 1200, 75 | }, 76 | responsive: true, 77 | maintainAspectRatio: false, 78 | rotation: 270, // start angle in degrees 79 | circumference: 180, // sweep angle in degrees 80 | plugins: { 81 | datalabels: { 82 | color: '#e1eeff', 83 | }, 84 | legend: { 85 | display: false, 86 | }, 87 | title: { 88 | display: true, 89 | text: 'Heap Size Used / Heap Size Bytes', 90 | color: '#e1eeff', 91 | }, 92 | }, 93 | }; 94 | 95 | const data: ChartData<'doughnut'> = { 96 | labels: ['Heap Size Used (MB)', 'Heap Size Remaining (MB)'], 97 | datasets: [ 98 | { 99 | data: [chartData.heapSizeUsed, chartData.difference], 100 | backgroundColor: [ 101 | colors.translucent.comment, 102 | 'rgba(255, 255, 255, 0.01', 103 | ], 104 | borderColor: [colors.solid.comment, 'rgba(255, 255, 255, 0.05'], 105 | borderWidth: 1, 106 | }, 107 | ], 108 | }; 109 | 110 | return ( 111 |
112 | 113 |
114 | ); 115 | }; 116 | 117 | export default SpeedometerChart; 118 | -------------------------------------------------------------------------------- /client/Components/StackedBarChart.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect } from 'react'; 2 | import { Bar } from 'react-chartjs-2'; 3 | import { useState } from 'react'; 4 | import colors from '../colors'; 5 | import { 6 | Chart as ChartJS, 7 | CategoryScale, 8 | LinearScale, 9 | BarElement, 10 | Title, 11 | Tooltip, 12 | Legend, 13 | ChartOptions, 14 | ChartData, 15 | } from 'chart.js'; 16 | 17 | ChartJS.register( 18 | CategoryScale, 19 | LinearScale, 20 | BarElement, 21 | Title, 22 | Tooltip, 23 | Legend 24 | ); 25 | 26 | type MetricProps = { 27 | label: string; 28 | }; 29 | 30 | const initialData: ChartData<'bar'> = { 31 | datasets: [], 32 | }; 33 | 34 | const StackedBarChart: FC = (props) => { 35 | const [data, setData] = useState(initialData); 36 | 37 | const options: ChartOptions<'bar'> = { 38 | animation: { 39 | easing: 'easeInCubic', 40 | duration: 1200, 41 | }, 42 | plugins: { 43 | datalabels: { 44 | color: '#e1eeff', 45 | }, 46 | legend: { 47 | display: false, 48 | }, 49 | title: { 50 | display: true, 51 | text: 'User & System CPU Time', 52 | color: '#e1eeff', 53 | }, 54 | }, 55 | responsive: true, 56 | maintainAspectRatio: false, 57 | scales: { 58 | x: { 59 | stacked: true, 60 | display: false, 61 | }, 62 | y: { 63 | stacked: true, 64 | title: { 65 | display: true, 66 | text: 'seconds', 67 | }, 68 | }, 69 | }, 70 | }; 71 | 72 | // upon component load, fetch general cluster metrics to render CPU bar component 73 | useEffect(() => { 74 | fetch('../api/dashboard/general') 75 | .then((res) => res.json()) 76 | .then((data) => { 77 | const data1 = data.totalSystemCpu.toFixed(2); 78 | const data2 = data.totalUserSystemCpu.toFixed(2); 79 | const newData: ChartData<'bar'> = { 80 | labels: [props.label], 81 | datasets: [ 82 | { 83 | label: 'total user CPU time', 84 | data: [data1], 85 | backgroundColor: colors.translucent.cyan, 86 | borderColor: colors.solid.cyan, 87 | }, 88 | { 89 | label: 'total system CPU time', 90 | data: [data2], 91 | backgroundColor: colors.translucent.purple, 92 | borderColor: colors.solid.purple, 93 | }, 94 | ], 95 | }; 96 | setData(newData); 97 | }) 98 | .catch((err) => console.log(err)); 99 | }, []); 100 | 101 | return ( 102 |
103 | 104 |
105 | ); 106 | }; 107 | 108 | export default StackedBarChart; 109 | -------------------------------------------------------------------------------- /client/Components/VisualizerTab.tsx: -------------------------------------------------------------------------------- 1 | import Avatar from '@mui/material/Avatar'; 2 | import Chip from '@mui/material/Chip'; 3 | import Stack from '@mui/material/Stack'; 4 | import React, { useState, useEffect } from 'react'; 5 | import CytoscapeComponent from 'react-cytoscapejs'; 6 | import colors from '../colors'; 7 | import { kubesColors } from '../colors'; 8 | 9 | const VisualizerTab = () => { 10 | const [elements, setElements] = useState([]); 11 | 12 | // upon component load, fetch network relational data and set state for these elements 13 | useEffect(() => { 14 | fetch('/api/hierarchy') 15 | .then((response) => response.json()) 16 | .then((data) => setElements(data)); 17 | }, []); 18 | 19 | const styleSheet = [ 20 | { 21 | selector: 'node', 22 | style: { 23 | color: 'white', 24 | label: 'data(label)', 25 | }, 26 | }, 27 | { 28 | selector: "node[type='namespace']", 29 | style: { 30 | 'border-width': '3px', 31 | 'border-color': 'black', 32 | shape: 'rectangle', 33 | 'background-color': colors.pastel.solid.envy, 34 | }, 35 | }, 36 | { 37 | selector: "node[type='pod']", 38 | style: { 39 | 'border-width': '3px', 40 | 'border-color': 'black', 41 | 'text-vertical-align': 'bottom', 42 | shape: 'circle', 43 | 'background-color': colors.pastel.solid.polo, 44 | }, 45 | }, 46 | { 47 | selector: "node[type='node']", 48 | style: { 49 | 'border-width': '3px', 50 | 'border-color': 'black', 51 | shape: 'triangle', 52 | 'background-color': kubesColors.purple, 53 | }, 54 | }, 55 | { 56 | selector: "node[type='service']", 57 | style: { 58 | 'border-width': '3px', 59 | 'border-color': 'black', 60 | shape: 'hexagon', 61 | 'background-color': colors.pastel.solid.martini, 62 | }, 63 | }, 64 | { 65 | selector: "node[type='deployment']", 66 | style: { 67 | 'border-width': '3px', 68 | 'border-color': 'black', 69 | shape: 'diamond', 70 | 'background-color': colors.pastel.solid.glacier, 71 | }, 72 | }, 73 | { 74 | selector: 'edge', 75 | style: { 76 | width: 3, 77 | 'line-color': colors.translucent.currentLine, 78 | }, 79 | }, 80 | ]; 81 | 82 | return ( 83 |
84 |
85 | 92 | } 94 | label="Nodes" 95 | variant="outlined" 96 | style={{ 97 | color: kubesColors.purple, 98 | borderColor: kubesColors.purple, 99 | }} 100 | /> 101 | } 103 | label="Namespaces" 104 | variant="outlined" 105 | style={{ 106 | color: colors.pastel.solid.envy, 107 | borderColor: colors.pastel.solid.envy, 108 | }} 109 | /> 110 | } 112 | label="Pods" 113 | variant="outlined" 114 | style={{ 115 | color: colors.pastel.solid.polo, 116 | borderColor: colors.pastel.solid.polo, 117 | }} 118 | /> 119 | } 121 | label="Services" 122 | variant="outlined" 123 | style={{ 124 | color: colors.pastel.solid.martini, 125 | borderColor: colors.pastel.solid.martini, 126 | }} 127 | /> 128 | } 130 | label="Deployments" 131 | variant="outlined" 132 | style={{ 133 | color: colors.pastel.solid.glacier, 134 | borderColor: colors.pastel.solid.glacier, 135 | }} 136 | /> 137 | 138 |
139 |
145 | 155 |
156 |
157 | ); 158 | }; 159 | 160 | export default VisualizerTab; 161 | -------------------------------------------------------------------------------- /client/colors.tsx: -------------------------------------------------------------------------------- 1 | const colors = { 2 | solid: { 3 | background: 'rgb(40, 42, 54)', 4 | currentLine: 'rgb(68, 71, 90)', 5 | foreground: 'rgb(248, 248, 242)', 6 | comment: 'rgb(98, 114, 164)', 7 | cyan: 'rgb(139, 233, 253)', 8 | green: 'rgb(80, 250, 123)', 9 | orange: 'rgb(255, 184, 108)', 10 | pink: 'rgb(255, 121, 198)', 11 | purple: 'rgb(189, 147, 249)', 12 | red: 'rgb(255, 85, 85)', 13 | yellow: 'rgb(241, 250, 140)', 14 | }, 15 | translucent: { 16 | background: 'rgba(40, 42, 54, 0.2)', 17 | currentLine: 'rgba(68, 71, 90, 0.2)', 18 | foreground: 'rgba(248, 248, 242, 0.2)', 19 | comment: 'rgba(98, 114, 164, 0.2)', 20 | cyan: 'rgba(139, 233, 253, 0.2)', 21 | green: 'rgba(80, 250, 123, 0.2)', 22 | orange: 'rgba(255, 184, 108, 0.2)', 23 | pink: 'rgba(255, 121, 198, 0.2)', 24 | purple: 'rgba(189, 147, 249, 0.2)', 25 | red: 'rgba(255, 85, 85, 0.2)', 26 | yellow: 'rgba(241, 250, 140, 0.2)', 27 | }, 28 | pastel: { 29 | solid: { 30 | envy: 'rgb(145, 172, 154)', 31 | opal: 'rgb(169, 195, 182)', 32 | geyser: 'rgb(206, 223, 223)', 33 | junglemist: 'rgb(183, 209, 211)', 34 | casper: 'rgb(166, 195, 206)', 35 | glacier: 'rgb(143,184,202)', 36 | polo: 'rgb(141, 159, 198)', 37 | martini: 'rgb(185, 162, 170)', 38 | }, 39 | translucent: { 40 | envy: 'rgba(145, 172, 154, 0.2)', 41 | opal: 'rgba(169, 195, 182, 0.2)', 42 | geyser: 'rgba(206, 223, 223, 0.2)', 43 | junglemist: 'rgba(183, 209, 211, 0.2)', 44 | casper: 'rgba(166, 195, 206, 0.2)', 45 | glacier: 'rgba(143,184,202, 0.2)', 46 | polo: 'rgba(141, 159, 198, 0.2)', 47 | martini: 'rgba(185, 162, 170, 0.2)', 48 | }, 49 | }, 50 | }; 51 | 52 | export const kubesColors = { 53 | purple: 'rgba(81,77,110, 1)', 54 | blue: 'rgba(95,121,156,0.6)', 55 | }; 56 | 57 | export default colors; 58 | -------------------------------------------------------------------------------- /client/dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oslabs-beta/KubernOcular/80b2fa8a105d0c40634c4dc54249c8960a608a8d/client/dark.png -------------------------------------------------------------------------------- /client/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oslabs-beta/KubernOcular/80b2fa8a105d0c40634c4dc54249c8960a608a8d/client/favicon.ico -------------------------------------------------------------------------------- /client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | KubernOcular 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /client/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { createRoot } from 'react-dom/client'; 3 | import App from './App'; 4 | import { BrowserRouter } from 'react-router-dom'; 5 | 6 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 7 | const root = createRoot(document.getElementById('root')!); 8 | root.render( 9 | 10 | 11 | 12 | ); 13 | -------------------------------------------------------------------------------- /client/light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oslabs-beta/KubernOcular/80b2fa8a105d0c40634c4dc54249c8960a608a8d/client/light.png -------------------------------------------------------------------------------- /client/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: rgb(25, 25, 25); 3 | color: white; 4 | } 5 | 6 | p { 7 | display: flex; 8 | flex-direction: column; 9 | text-align: left; 10 | } 11 | 12 | #logo-icon { 13 | max-height: 30px; 14 | margin-left: -10px; 15 | } 16 | 17 | #logo { 18 | max-height: 40px; 19 | } 20 | 21 | .logo-link { 22 | display: flex; 23 | align-items: center; 24 | } 25 | 26 | #kubernocular-logo { 27 | max-height: 50px; 28 | object-fit: contain; 29 | } 30 | 31 | #metric-graphs { 32 | display: flex; 33 | flex-wrap: wrap; 34 | width: 100%; 35 | align-items: center; 36 | justify-content: center; 37 | } 38 | 39 | .graph, 40 | .loading, 41 | .error { 42 | padding: 1vw; 43 | margin: 10px; 44 | width: 40vw; 45 | box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px; 46 | border-radius: 10px; 47 | } 48 | 49 | .loading { 50 | display: flex; 51 | min-height: 300px; 52 | justify-content: center; 53 | align-items: center; 54 | } 55 | 56 | .error { 57 | display: flex; 58 | justify-content: center; 59 | align-items: center; 60 | flex-direction: column; 61 | } 62 | 63 | .warning-icon { 64 | margin: 30px; 65 | } 66 | 67 | .error h5 { 68 | margin: 5px; 69 | } 70 | 71 | .error a:link { 72 | color: rgb(97, 117, 149); 73 | } 74 | 75 | .error a:visited { 76 | color: rgb(81, 78, 110); 77 | } 78 | 79 | .error-bottom { 80 | padding-bottom: 35px; 81 | } 82 | 83 | .MuiTableBody-root { 84 | cursor: pointer; 85 | } 86 | 87 | #instant-metrics-container { 88 | display: flex; 89 | flex-direction: row; 90 | justify-content: space-between; 91 | align-self: center; 92 | width: 81vw; 93 | background-image: linear-gradient( 94 | rgba(255, 255, 255, 0.09), 95 | rgba(255, 255, 255, 0.09) 96 | ); 97 | box-shadow: 0px 2px 4px -1px rgb(0 0 0 / 20%), 98 | 0px 4px 5px 0px rgb(0 0 0 / 14%), 0px 1px 10px 0px rgb(0 0 0 / 12%); 99 | border-radius: 10px; 100 | } 101 | 102 | #db-container { 103 | display: flex; 104 | flex-direction: column; 105 | } 106 | 107 | #nav-instant-metrics-table { 108 | display: grid; 109 | grid-template-columns: auto auto auto; 110 | font-size: 0.7vw; 111 | } 112 | 113 | .metric-box { 114 | display: flex; 115 | flex-direction: column; 116 | justify-content: center; 117 | align-items: center; 118 | background-image: linear-gradient( 119 | rgba(255, 255, 255, 0.09), 120 | rgba(255, 255, 255, 0.09) 121 | ); 122 | border-radius: 10px; 123 | margin: 0.5vw; 124 | width: 5vw; 125 | } 126 | 127 | .metric-label { 128 | padding: 0.25vw; 129 | } 130 | 131 | .instant-metric-comp { 132 | padding: 0.5vw; 133 | width: 24%; 134 | } 135 | 136 | #stacked-bar-chart { 137 | width: 20%; 138 | } 139 | -------------------------------------------------------------------------------- /jest-teardown.ts: -------------------------------------------------------------------------------- 1 | module.exports = () => { 2 | process.exit(0); 3 | }; 4 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * For a detailed explanation regarding each configuration property and type check, visit: 3 | * https://jestjs.io/docs/configuration 4 | */ 5 | 6 | export default { 7 | // All imported modules in your tests should be mocked automatically 8 | // automock: false, 9 | 10 | // Stop running tests after `n` failures 11 | // bail: 0, 12 | 13 | // The directory where Jest should store its cached dependency information 14 | // cacheDirectory: "/tmp/jest_rs", 15 | 16 | // Automatically clear mock calls, instances, contexts and results before every test 17 | clearMocks: true, 18 | 19 | // Indicates whether the coverage information should be collected while executing the test 20 | // collectCoverage: false, 21 | 22 | // An array of glob patterns indicating a set of files for which coverage information should be collected 23 | // collectCoverageFrom: undefined, 24 | 25 | // The directory where Jest should output its coverage files 26 | // coverageDirectory: undefined, 27 | 28 | // An array of regexp pattern strings used to skip coverage collection 29 | // coveragePathIgnorePatterns: [ 30 | // "/node_modules/" 31 | // ], 32 | 33 | // Indicates which provider should be used to instrument code for coverage 34 | coverageProvider: 'v8', 35 | 36 | // A list of reporter names that Jest uses when writing coverage reports 37 | // coverageReporters: [ 38 | // "json", 39 | // "text", 40 | // "lcov", 41 | // "clover" 42 | // ], 43 | 44 | // An object that configures minimum threshold enforcement for coverage results 45 | // coverageThreshold: undefined, 46 | 47 | // A path to a custom dependency extractor 48 | // dependencyExtractor: undefined, 49 | 50 | // Make calling deprecated APIs throw helpful error messages 51 | // errorOnDeprecated: false, 52 | 53 | // The default configuration for fake timers 54 | // fakeTimers: { 55 | // "enableGlobally": false 56 | // }, 57 | 58 | // Force coverage collection from ignored files using an array of glob patterns 59 | // forceCoverageMatch: [], 60 | 61 | // A path to a module which exports an async function that is triggered once before all test suites 62 | // globalSetup: './jest-setup.ts', 63 | 64 | // A path to a module which exports an async function that is triggered once after all test suites 65 | globalTeardown: './jest-teardown.ts', 66 | 67 | // A set of global variables that need to be available in all test environments 68 | // globals: {}, 69 | 70 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 71 | // maxWorkers: "50%", 72 | 73 | // An array of directory names to be searched recursively up from the requiring module's location 74 | // moduleDirectories: [ 75 | // "node_modules" 76 | // ], 77 | 78 | // An array of file extensions your modules use 79 | // moduleFileExtensions: [ 80 | // "js", 81 | // "mjs", 82 | // "cjs", 83 | // "jsx", 84 | // "ts", 85 | // "tsx", 86 | // "json", 87 | // "node" 88 | // ], 89 | 90 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 91 | // moduleNameMapper: {}, 92 | 93 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 94 | // modulePathIgnorePatterns: [], 95 | 96 | // Activates notifications for test results 97 | // notify: false, 98 | 99 | // An enum that specifies notification mode. Requires { notify: true } 100 | // notifyMode: "failure-change", 101 | 102 | // A preset that is used as a base for Jest's configuration 103 | // preset: undefined, 104 | 105 | // Run tests from one or more projects 106 | // projects: undefined, 107 | 108 | // Use this configuration option to add custom reporters to Jest 109 | // reporters: undefined, 110 | 111 | // Automatically reset mock state before every test 112 | // resetMocks: false, 113 | 114 | // Reset the module registry before running each individual test 115 | // resetModules: false, 116 | 117 | // A path to a custom resolver 118 | // resolver: undefined, 119 | 120 | // Automatically restore mock state and implementation before every test 121 | // restoreMocks: false, 122 | 123 | // The root directory that Jest should scan for tests and modules within 124 | // rootDir: undefined, 125 | 126 | // A list of paths to directories that Jest should use to search for files in 127 | // roots: [ 128 | // "" 129 | // ], 130 | 131 | // Allows you to use a custom runner instead of Jest's default test runner 132 | // runner: "jest-runner", 133 | 134 | // The paths to modules that run some code to configure or set up the testing environment before each test 135 | // setupFiles: [], 136 | 137 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 138 | // setupFilesAfterEnv: [], 139 | 140 | // The number of seconds after which a test is considered as slow and reported as such in the results. 141 | // slowTestThreshold: 5, 142 | 143 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 144 | // snapshotSerializers: [], 145 | 146 | // The test environment that will be used for testing 147 | // testEnvironment: "jest-environment-node", 148 | 149 | // Options that will be passed to the testEnvironment 150 | // testEnvironmentOptions: {}, 151 | 152 | // Adds a location field to test results 153 | // testLocationInResults: false, 154 | 155 | // The glob patterns Jest uses to detect test files 156 | // testMatch: [ 157 | // "**/__tests__/**/*.[jt]s?(x)", 158 | // "**/?(*.)+(spec|test).[tj]s?(x)" 159 | // ], 160 | 161 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 162 | // testPathIgnorePatterns: [ 163 | // "/node_modules/" 164 | // ], 165 | 166 | // The regexp pattern or array of patterns that Jest uses to detect test files 167 | // testRegex: [], 168 | 169 | // This option allows the use of a custom results processor 170 | // testResultsProcessor: undefined, 171 | 172 | // This option allows use of a custom test runner 173 | // testRunner: "jest-circus/runner", 174 | 175 | // A map from regular expressions to paths to transformers 176 | // transform: undefined, 177 | 178 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 179 | // transformIgnorePatterns: [ 180 | // "/node_modules/", 181 | // "\\.pnp\\.[^\\/]+$" 182 | // ], 183 | 184 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 185 | // unmockedModulePathPatterns: undefined, 186 | 187 | // Indicates whether each individual test should be reported during the run 188 | // verbose: undefined, 189 | 190 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 191 | // watchPathIgnorePatterns: [], 192 | 193 | // Whether to use watchman for file crawling 194 | // watchman: true, 195 | }; 196 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "kubernocular", 3 | "version": "1.0.0", 4 | "description": "## readme in construction", 5 | "main": "server.ts", 6 | "scripts": { 7 | "test": "jest", 8 | "build": "NODE_ENV=production webpack", 9 | "start": "nodemon server/server.ts", 10 | "dev": "webpack-dev-server & nodemon server/server.ts", 11 | "lint": "eslint . --ext .ts" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/oslabs-beta/KubernOcular.git" 16 | }, 17 | "keywords": [], 18 | "author": "", 19 | "license": "ISC", 20 | "bugs": { 21 | "url": "https://github.com/oslabs-beta/KubernOcular/issues" 22 | }, 23 | "homepage": "https://github.com/oslabs-beta/KubernOcular#readme", 24 | "dependencies": { 25 | "@babel/preset-env": "^7.19.3", 26 | "@babel/preset-typescript": "^7.18.6", 27 | "@emotion/react": "^11.10.4", 28 | "@emotion/styled": "^11.10.4", 29 | "@kubernetes/client-node": "^0.17.1", 30 | "@mui/icons-material": "^5.10.6", 31 | "@mui/material": "^5.10.7", 32 | "@types/react-cytoscapejs": "^1.2.2", 33 | "axios": "^0.27.2", 34 | "chart.js": "^3.9.1", 35 | "chartjs-gauge": "^0.3.0", 36 | "chartjs-plugin-datalabels": "^2.1.0", 37 | "cors": "^2.8.5", 38 | "cytoscape": "^3.23.0", 39 | "express": "^4.18.1", 40 | "node-fetch": "^3.2.10", 41 | "nodemon": "^2.0.20", 42 | "prom-client": "^14.1.0", 43 | "react": "^18.2.0", 44 | "react-chartjs-2": "^4.3.1", 45 | "react-cytoscapejs": "^2.0.0", 46 | "react-dom": "^18.2.0", 47 | "react-router-dom": "^6.4.1", 48 | "ts-node": "^10.9.1", 49 | "typescript": "^4.8.3" 50 | }, 51 | "devDependencies": { 52 | "@testing-library/react": "^13.4.0", 53 | "@testing-library/user-event": "^14.4.3", 54 | "@types/cors": "^2.8.12", 55 | "@types/cytoscape": "^3.19.9", 56 | "@types/express": "^4.17.14", 57 | "@types/jest": "^29.1.1", 58 | "@types/node": "^18.7.20", 59 | "@types/react": "^18.0.21", 60 | "@types/react-dom": "^18.0.6", 61 | "@typescript-eslint/eslint-plugin": "^5.40.0", 62 | "@typescript-eslint/parser": "^5.40.0", 63 | "copy-webpack-plugin": "^11.0.0", 64 | "css-loader": "^6.7.1", 65 | "enzyme": "^3.11.0", 66 | "eslint": "^8.25.0", 67 | "file-loader": "^6.2.0", 68 | "html-webpack-plugin": "^5.5.0", 69 | "img-loader": "^4.0.0", 70 | "jest": "^29.1.1", 71 | "postcss-loader": "^7.0.1", 72 | "prettier": "2.7.1", 73 | "puppeteer": "^18.0.5", 74 | "regenerator-runtime": "^0.13.9", 75 | "style-loader": "^3.3.1", 76 | "supertest": "^6.2.4", 77 | "ts-jest": "^29.0.3", 78 | "ts-loader": "^9.4.1", 79 | "webpack-cli": "^4.10.0", 80 | "webpack-dev-server": "^4.11.1" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /server/controllers/clusterController.ts: -------------------------------------------------------------------------------- 1 | import { ClusterController, k8s } from '../../types'; 2 | const kc = new k8s.KubeConfig(); 3 | kc.loadFromDefault(); 4 | const k8sApi = kc.makeApiClient(k8s.CoreV1Api); 5 | 6 | const clusterController: ClusterController = { 7 | getNamespaces: (req, res, next) => { 8 | k8sApi 9 | .listNamespace() 10 | .then((data: any) => { 11 | const output: string[] = []; 12 | for (const element of data.body.items) { 13 | output.push(element.metadata.name); 14 | } 15 | res.locals.namespaces = output; 16 | return next(); 17 | }) 18 | .catch((err: string | null) => 19 | next({ 20 | log: `Error in clusterController.getNamespaces middleware: ${err}`, 21 | status: 500, 22 | message: { err: 'An error occurred' }, 23 | }) 24 | ); 25 | }, 26 | 27 | getPodsByNamespace: (req, res, next) => { 28 | const { namespace } = req.query; 29 | k8sApi 30 | .listNamespacedPod(namespace) 31 | .then((data: any) => { 32 | const output: string[] = []; 33 | for (const element of data.body.items) { 34 | output.push(element.metadata.name); 35 | } 36 | res.locals.pods = output; 37 | return next(); 38 | }) 39 | .catch((err: string | null) => 40 | next({ 41 | log: `Error in clusterController.getPodsByNamespace middleware: ${err}`, 42 | status: 500, 43 | message: { 44 | err: 'An error occurred while getting pods by namespace', 45 | }, 46 | }) 47 | ); 48 | }, 49 | 50 | getNodes: (req, res, next) => { 51 | k8sApi 52 | .listNode() 53 | .then((data: any) => { 54 | const output = []; 55 | for (const element of data.body.items) { 56 | type Names = { 57 | name: string; 58 | ip: string; 59 | }; 60 | const names: Names = { 61 | name: '', 62 | ip: '', 63 | }; 64 | for (const el of element.status.addresses) { 65 | if (el.type === 'Hostname') { 66 | names.name = el.address; 67 | } else if (el.type === 'InternalIP') { 68 | names.ip = el.address; 69 | } 70 | } 71 | output.push(names); 72 | } 73 | res.locals.nodes = output; 74 | return next(); 75 | }) 76 | .catch((err: string | null) => 77 | next({ 78 | log: `Error in clusterController.getNodes middleware: ${err}`, 79 | status: 500, 80 | message: { 81 | err: 'An error occurred while getting all node names', 82 | }, 83 | }) 84 | ); 85 | }, 86 | }; 87 | 88 | export default clusterController; 89 | -------------------------------------------------------------------------------- /server/controllers/customController.ts: -------------------------------------------------------------------------------- 1 | import { start, end, CustomController, axios, CustomQuery } from '../../types'; 2 | 3 | const customController: CustomController = { 4 | 5 | // these arrays store all custom queries scoped by namespace 6 | customClusterQueries: [], 7 | customNodeQueries: [], 8 | customPodQueries: [], 9 | 10 | testCustomRoute: async (req, res, next) => { 11 | const { query, scope } = req.body; 12 | try { 13 | const data = await axios.get( 14 | `http://localhost:9090/api/v1/query?query=${query}` 15 | ); 16 | if (scope === 'cluster') { 17 | if ( 18 | data.data.status === 'success' && 19 | data.data.data.result.length === 1 20 | ) { 21 | res.locals.valid = true; 22 | } else { 23 | res.locals.valid = false; 24 | } 25 | } else if (scope === 'pod') { 26 | if ( 27 | data.data.status === 'success' && 28 | data.data.data.result.length && 29 | data.data.data.result[0].metric.pod 30 | ) { 31 | res.locals.valid = true; 32 | } else { 33 | res.locals.valid = false; 34 | } 35 | } else if (scope === 'node') { 36 | if ( 37 | data.data.status === 'success' && 38 | data.data.data.result.length && 39 | data.data.data.result[0].metric.job === 'node-exporter' 40 | ) { 41 | res.locals.valid = true; 42 | req.body.query = `sum(${query})by(instance)`; 43 | } else { 44 | res.locals.valid = false; 45 | } 46 | } else { 47 | res.locals.valid = false; 48 | } 49 | return next(); 50 | } catch (err) { 51 | return next({ 52 | log: `Error in customController.testCustomRoute: ${err}`, 53 | status: 500, 54 | message: { 55 | err: 'Error occured while testing custom query route', 56 | }, 57 | }); 58 | } 59 | }, 60 | 61 | addCustomRoute: async (req, res, next) => { 62 | try { 63 | if (res.locals.valid) { 64 | const { query, name, scope } = req.body; 65 | const yAxisType = 66 | req.body.yAxisType === 'null' ? '' : req.body.yAxisType; 67 | let scopedQueries: CustomQuery[] = []; 68 | if (scope === 'cluster') 69 | scopedQueries = customController.customClusterQueries; 70 | else if (scope === 'node') 71 | scopedQueries = customController.customNodeQueries; 72 | else if (scope === 'pod') 73 | scopedQueries = customController.customPodQueries; 74 | else throw 'Scope parameter must be defined as cluster, node, or pod'; 75 | scopedQueries.push({ 76 | query, 77 | name, 78 | yAxisType, 79 | active: true, 80 | }); 81 | res.locals.addedRoute = true; 82 | } else { 83 | res.locals.addedRoute = false; 84 | } 85 | return next(); 86 | } catch (err) { 87 | return next({ 88 | log: `Error in customController.addCustomRoute: ${err}`, 89 | status: 500, 90 | message: { 91 | err: 'Error occured while adding custom query route', 92 | }, 93 | }); 94 | } 95 | }, 96 | 97 | // frontend components use this route to get data from custom queries 98 | getCustomRoute: async (req, res, next) => { 99 | try { 100 | const { scope, index, pod, nodeIP } = req.query; 101 | let scopedQueries: CustomQuery[] = []; 102 | if (scope === 'cluster') 103 | scopedQueries = customController.customClusterQueries; 104 | else if (scope === 'node') 105 | scopedQueries = customController.customNodeQueries; 106 | else if (scope === 'pod') 107 | scopedQueries = customController.customPodQueries; 108 | else throw 'Scope parameter must be defined as cluster, node, or pod'; 109 | // resolve custom queries here 110 | const query = scopedQueries[Number(index)].query; 111 | const result = await axios.get( 112 | `http://localhost:9090/api/v1/query_range?query=${query}&start=${start}&end=${end}&step=10m` 113 | ); 114 | if (scope === 'pod') { 115 | result.data.data.result = result.data.data.result.filter( 116 | (podMetric: any) => podMetric.metric.pod === pod 117 | ); 118 | } else if (scope === 'node') { 119 | result.data.data.result = result.data.data.result.filter( 120 | (nodeMetric: any) => nodeMetric.metric.instance === `${nodeIP}:9100` 121 | ); 122 | } 123 | res.locals.data = result.data; 124 | return next(); 125 | } catch (err) { 126 | return next({ 127 | log: `Error in customController.getCustomRoute: ${err}`, 128 | status: 500, 129 | message: { 130 | err: 'Error occured while getting custom query', 131 | }, 132 | }); 133 | } 134 | }, 135 | 136 | // the custom query list and custom query renderers use this to list custom queries 137 | listCustomRoutes: async (req, res, next) => { 138 | try { 139 | const { scope } = req.query; 140 | let scopedQueries: CustomQuery[] = []; 141 | if (scope === 'cluster') 142 | scopedQueries = customController.customClusterQueries; 143 | else if (scope === 'node') 144 | scopedQueries = customController.customNodeQueries; 145 | else if (scope === 'pod') 146 | scopedQueries = customController.customPodQueries; 147 | else throw 'Scope parameter must be defined as cluster, node, or pod'; 148 | res.locals.data = scopedQueries; 149 | return next(); 150 | } catch (err) { 151 | return next({ 152 | log: `Error in customController.getCustomRoutes: ${err}`, 153 | status: 500, 154 | message: { 155 | err: 'Error occured while getting custom queries', 156 | }, 157 | }); 158 | } 159 | }, 160 | 161 | deleteCustomRoute: async (req, res, next) => { 162 | try { 163 | const { scope, id } = req.body; 164 | let scopedQueries: CustomQuery[] = []; 165 | if (scope === 'cluster') 166 | scopedQueries = customController.customClusterQueries; 167 | else if (scope === 'node') 168 | scopedQueries = customController.customNodeQueries; 169 | else if (scope === 'pod') 170 | scopedQueries = customController.customPodQueries; 171 | else throw 'Scope parameter must be defined as cluster, node, or pod'; 172 | const initLen = scopedQueries.length; 173 | res.locals.route = scopedQueries[id]; 174 | scopedQueries.splice(id, 1); 175 | const currentLen = scopedQueries.length; 176 | res.locals.deletedRoute = initLen === currentLen ? false : true; 177 | return next(); 178 | } catch (err) { 179 | return next({ 180 | log: `Error in customController.deleteCustomRoute: ${err}`, 181 | status: 500, 182 | message: { 183 | err: 'Error occured while deleting custom query', 184 | }, 185 | }); 186 | } 187 | }, 188 | 189 | // this route triggers when user presses the checkbox for a custom query 190 | changeRouteActive: async (req, res, next) => { 191 | try { 192 | const { scope, id, active } = req.body; 193 | let scopedQueries: CustomQuery[] = []; 194 | if (scope === 'cluster') 195 | scopedQueries = customController.customClusterQueries; 196 | else if (scope === 'node') 197 | scopedQueries = customController.customNodeQueries; 198 | else if (scope === 'pod') 199 | scopedQueries = customController.customPodQueries; 200 | else throw 'Scope parameter must be defined as cluster, node, or pod'; 201 | scopedQueries[id].active = active; 202 | return next(); 203 | } catch (err) { 204 | return next({ 205 | log: `Error in customController.deleteCustomRoute: ${err}`, 206 | status: 500, 207 | message: { 208 | err: 'Error occured while deleting custom query', 209 | }, 210 | }); 211 | } 212 | }, 213 | }; 214 | 215 | export default customController; 216 | -------------------------------------------------------------------------------- /server/controllers/dashboardController.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DashboardController, 3 | NumOfData, 4 | GeneralData, 5 | start, 6 | end, 7 | axios, 8 | k8s, 9 | client, 10 | } from '../../types'; 11 | const kc = new k8s.KubeConfig(); 12 | kc.loadFromDefault(); 13 | const k8sApi = kc.makeApiClient(k8s.CoreV1Api); 14 | const k8sApi1 = kc.makeApiClient(k8s.AppsV1Api); 15 | const k8sApi3 = kc.makeApiClient(k8s.NetworkingV1Api); 16 | client.collectDefaultMetrics(); 17 | 18 | // dashboard makes all these queries to populate data on load 19 | const dashboardController: DashboardController = { 20 | getNumberOf: async (req, res, next) => { 21 | const [ 22 | nodeList, 23 | podList, 24 | namespaceList, 25 | deploymentList, 26 | ingressList, 27 | serviceList, 28 | ] = [ 29 | k8sApi.listNode(), 30 | k8sApi.listPodForAllNamespaces(), 31 | k8sApi.listNamespace(), 32 | k8sApi1.listDeploymentForAllNamespaces(), 33 | k8sApi3.listIngressForAllNamespaces(), 34 | k8sApi.listServiceForAllNamespaces(), 35 | ]; 36 | 37 | const data = await Promise.all([ 38 | nodeList, 39 | podList, 40 | namespaceList, 41 | deploymentList, 42 | ingressList, 43 | serviceList, 44 | ]); 45 | const numOfData: NumOfData = { 46 | nodes: data[0].body.items.length, 47 | pods: data[1].body.items.length, 48 | namespaces: data[2].body.items.length, 49 | deployments: data[3].body.items.length, 50 | ingresses: data[4].body.items.length, 51 | services: data[5].body.items.length, 52 | }; 53 | 54 | res.locals.data = numOfData; 55 | return next(); 56 | }, 57 | 58 | getGeneralClusterInfo: async (req, res, next) => { 59 | const generalData: GeneralData = { 60 | totalUserCpu: 0, 61 | totalSystemCpu: 0, 62 | totalUserSystemCpu: 0, 63 | residentMemBytes: 0, 64 | eventLoopLag: 0, 65 | totalActiveResources: 0, 66 | totalActiveHandles: 0, 67 | totalActiveRequests: 0, 68 | heapSizeBytes: 0, 69 | heapSizeUsed: 0, 70 | }; 71 | client.register.getMetricsAsJSON().then((data: any) => { 72 | generalData.totalUserCpu = data[0].values[0].value; 73 | generalData.totalSystemCpu = data[1].values[0].value; 74 | generalData.totalUserSystemCpu = data[2].values[0].value; 75 | generalData.residentMemBytes = data[4].values[0].value; 76 | generalData.eventLoopLag = data[5].values[0].value; 77 | generalData.totalActiveResources = data[14].values[0].value; 78 | generalData.totalActiveHandles = data[16].values[0].value; 79 | generalData.totalActiveRequests = data[18].values[0].value; 80 | generalData.heapSizeBytes = data[19].values[0].value; 81 | generalData.heapSizeUsed = data[20].values[0].value; 82 | res.locals.data = generalData; 83 | return next(); 84 | }); 85 | }, 86 | 87 | getTotalMem: async (req, res, next) => { 88 | try { 89 | const data = await axios.get( 90 | `http://localhost:9090/api/v1/query_range?query=sum(container_memory_usage_bytes)&start=${start}&end=${end}&step=10m` 91 | ); 92 | res.locals.totalMem = data; 93 | return next(); 94 | } catch (err) { 95 | return next({ 96 | log: `Error in dashboardController.getTotalMem: ${err}`, 97 | status: 500, 98 | message: { 99 | err: 'Error occured while retrieving dashboard memory data', 100 | }, 101 | }); 102 | } 103 | }, 104 | 105 | getTotalCpu: async (req, res, next) => { 106 | try { 107 | const data = await axios.get( 108 | `http://localhost:9090/api/v1/query_range?query=sum(rate(container_cpu_usage_seconds_total[10m]))*100&start=${start}&end=${end}&step=10m` 109 | ); 110 | res.locals.totalCpu = data; 111 | return next(); 112 | } catch (err) { 113 | return next({ 114 | log: `Error in dashboardController.getTotalCpu: ${err}`, 115 | status: 500, 116 | message: { 117 | err: 'Error occured while retrieving dashboard cpu data', 118 | }, 119 | }); 120 | } 121 | }, 122 | 123 | getTotalTransmit: async (req, res, next) => { 124 | try { 125 | const data = await axios.get( 126 | `http://localhost:9090/api/v1/query_range?query=sum(rate(node_network_transmit_bytes_total[10m]))&start=${start}&end=${end}&step=10m` 127 | ); 128 | res.locals.totalTransmit = data; 129 | return next(); 130 | } catch (err) { 131 | return next({ 132 | log: `Error in dashboardController.getTotalTransmit: ${err}`, 133 | status: 500, 134 | message: { 135 | err: 'Error occured while retrieving dashboard bytes transmit data', 136 | }, 137 | }); 138 | } 139 | }, 140 | 141 | getTotalReceive: async (req, res, next) => { 142 | try { 143 | const data = await axios.get( 144 | `http://localhost:9090/api/v1/query_range?query=sum(rate(node_network_receive_bytes_total[10m]))&start=${start}&end=${end}&step=10m` 145 | ); 146 | res.locals.totalReceive = data; 147 | return next(); 148 | } catch (err) { 149 | return next({ 150 | log: `Error in dashboardController.getTotalReceive: ${err}`, 151 | status: 500, 152 | message: { 153 | err: 'Error occured while retrieving dashboard bytes receive data', 154 | }, 155 | }); 156 | } 157 | }, 158 | }; 159 | 160 | export default dashboardController; 161 | -------------------------------------------------------------------------------- /server/controllers/hierarchyController.ts: -------------------------------------------------------------------------------- 1 | import { HierarchyController, Elements, k8s } from '../../types'; 2 | const kc = new k8s.KubeConfig(); 3 | kc.loadFromDefault(); 4 | const k8sApi = kc.makeApiClient(k8s.CoreV1Api); 5 | const k8sApi1 = kc.makeApiClient(k8s.AppsV1Api); 6 | 7 | const hierarchyController: HierarchyController = { 8 | getElements: async (req, res, next) => { 9 | try { 10 | const elements: Elements[] = []; 11 | 12 | const namespaceData = await k8sApi.listNamespace(); 13 | 14 | let distance = 1280 / (namespaceData.body.items.length + 1); 15 | let multiplier = 1; 16 | 17 | const namespaces: string[] = []; 18 | namespaceData.body.items.forEach((space: any) => { 19 | const name = space.metadata.name; 20 | if (name !== 'kube-system') namespaces.push(name); 21 | elements.push({ 22 | data: { 23 | id: name, 24 | label: name, 25 | type: 'namespace', 26 | }, 27 | position: { 28 | x: distance * multiplier, 29 | y: 175, 30 | }, 31 | }); 32 | multiplier++; 33 | }); 34 | 35 | const len = await k8sApi.listPodForAllNamespaces(); 36 | distance = 2560 / (len.body.items.length + 1); 37 | multiplier = 1; 38 | let alter = false; 39 | 40 | const nodeSet = new Set(); 41 | const srvSet = new Set(); 42 | const deplSet = new Set(); 43 | 44 | for (const namespace of namespaces) { 45 | const podData = await k8sApi.listNamespacedPod(namespace); 46 | // eslint-disable-next-line no-loop-func 47 | podData.body.items.forEach((pod: any) => { 48 | const yVal = alter ? 250 : 350; 49 | const name = pod.metadata.name; 50 | elements.push({ 51 | data: { 52 | id: name, 53 | label: name, 54 | type: 'pod', 55 | }, 56 | position: { 57 | x: distance * multiplier, 58 | y: yVal, 59 | }, 60 | }); 61 | multiplier++; 62 | elements.push({ 63 | data: { 64 | source: name, 65 | target: namespace, 66 | }, 67 | }); 68 | alter = alter ? false : true; 69 | }); 70 | 71 | const nodeData = await k8sApi.listNode(namespace); 72 | const lenNode = await k8sApi.listNode(); 73 | distance = 1280 / (lenNode.body.items.length + 1); 74 | multiplier = 1; 75 | // eslint-disable-next-line no-loop-func 76 | nodeData.body.items.forEach((node: any) => { 77 | const yVal = alter ? 0 : 50; 78 | const name = node.metadata.name; 79 | if (!nodeSet.has(name)) { 80 | elements.push({ 81 | data: { 82 | id: name, 83 | label: name, 84 | type: 'node', 85 | }, 86 | position: { 87 | x: distance * multiplier, 88 | y: yVal, 89 | }, 90 | }); 91 | multiplier++; 92 | nodeSet.add(name); 93 | } 94 | elements.push({ 95 | data: { 96 | source: name, 97 | target: namespace, 98 | }, 99 | }); 100 | alter = alter ? false : true; 101 | }); 102 | 103 | const lenSrv = await k8sApi.listServiceForAllNamespaces(); 104 | distance = 2560 / (lenSrv.body.items.length + 1); 105 | 106 | const serviceData = await k8sApi.listNamespacedService(namespace); 107 | // eslint-disable-next-line no-loop-func 108 | serviceData.body.items.forEach((service: any) => { 109 | const yVal = alter ? 450 : 525; 110 | const name = service.metadata.name; 111 | if (!srvSet.has(name)) { 112 | elements.push({ 113 | data: { 114 | id: name, 115 | label: name, 116 | type: 'service', 117 | }, 118 | position: { 119 | x: distance * multiplier, 120 | y: yVal, 121 | }, 122 | }); 123 | multiplier++; 124 | srvSet.add(name); 125 | } 126 | elements.push({ 127 | data: { 128 | source: name, 129 | target: namespace, 130 | }, 131 | }); 132 | alter = alter ? false : true; 133 | }); 134 | 135 | const lenDep = await k8sApi1.listDeploymentForAllNamespaces(); 136 | distance = 2560 / (lenDep.body.items.length + 1); 137 | multiplier = 1; 138 | 139 | const deployData = await k8sApi1.listNamespacedDeployment(namespace); 140 | // eslint-disable-next-line no-loop-func 141 | deployData.body.items.forEach((deploy: any) => { 142 | const yVal = alter ? 575 : 625; 143 | const name = deploy.metadata.name + ' (depl)'; 144 | if (!deplSet.has(name)) { 145 | elements.push({ 146 | data: { 147 | id: name, 148 | label: name, 149 | type: 'deployment', 150 | }, 151 | position: { 152 | x: distance * multiplier, 153 | y: yVal, 154 | }, 155 | }); 156 | multiplier++; 157 | deplSet.add(name); 158 | } 159 | elements.push({ 160 | data: { 161 | source: name, 162 | target: namespace, 163 | }, 164 | }); 165 | alter = alter ? false : true; 166 | }); 167 | } 168 | 169 | res.locals.elements = elements; 170 | return next(); 171 | } catch (err) { 172 | return next({ 173 | log: `Error in hierarchyController.getElements: ${err}`, 174 | status: 500, 175 | message: { 176 | err: 'Error occured while retrieving network elements in hierarchyController', 177 | }, 178 | }); 179 | } 180 | }, 181 | }; 182 | 183 | export default hierarchyController; 184 | -------------------------------------------------------------------------------- /server/controllers/nodeController.ts: -------------------------------------------------------------------------------- 1 | import { start, end, NodeController, axios } from '../../types'; 2 | 3 | const nodeController: NodeController = { 4 | 5 | // node list queries this to populate instant metrics next to names 6 | getInstantMetrics: async (req, res, next) => { 7 | try { 8 | const responseTransmit = await axios.get( 9 | `http://localhost:9090/api/v1/query?query=sum(rate(node_network_transmit_bytes_total[10m]))by(instance)` 10 | ); 11 | const responseReceive = await axios.get( 12 | `http://localhost:9090/api/v1/query?query=sum(rate(node_network_receive_bytes_total[10m]))by(instance)` 13 | ); 14 | res.locals.data = {}; 15 | for (let i = 0; i < responseTransmit.data.data.result.length; i++) { 16 | res.locals.data[ 17 | responseTransmit.data.data.result[i].metric.instance.slice(0, -5) 18 | ] = { 19 | transmit: responseTransmit.data.data.result[i].value[1], 20 | receive: responseReceive.data.data.result[i].value[1], 21 | }; 22 | } 23 | return next(); 24 | } catch (err) { 25 | return next({ 26 | log: `Error in nodeController.getInstantMetrics middleware: ${err}`, 27 | status: 500, 28 | message: { 29 | err: 'An error occurred in while getting node instant metrics', 30 | }, 31 | }); 32 | } 33 | }, 34 | 35 | // node display makes the following queries to display the preset metrics 36 | getNetworkTransmitBytes: async (req, res, next) => { 37 | const { nodeIP } = req.query; 38 | try { 39 | const data = await axios.get( 40 | `http://localhost:9090/api/v1/query_range?query=sum(rate(node_network_transmit_bytes_total{instance='${nodeIP}:9100'}[10m]))&start=${start}&end=${end}&step=10m` 41 | ); 42 | res.locals.transmitBytes = data; 43 | return next(); 44 | } catch (err) { 45 | return next({ 46 | log: `Error in nodeController.getNetworkTransmitBytes: ${err}`, 47 | status: 500, 48 | message: { 49 | err: 'Error occured while retrieving node transmit bytes data', 50 | }, 51 | }); 52 | } 53 | }, 54 | 55 | getNetworkReceiveBytes: async (req, res, next) => { 56 | const { nodeIP } = req.query; 57 | try { 58 | const data = await axios.get( 59 | `http://localhost:9090/api/v1/query_range?query=sum(rate(node_network_receive_bytes_total{instance='${nodeIP}:9100'}[10m]))&start=${start}&end=${end}&step=10m` 60 | ); 61 | res.locals.receiveBytes = data; 62 | return next(); 63 | } catch (err) { 64 | return next({ 65 | log: `Error in nodeController.getNetworkRecieveBytes: ${err}`, 66 | status: 500, 67 | message: { 68 | err: 'Error occured while retrieving node recieve bytes data', 69 | }, 70 | }); 71 | } 72 | }, 73 | }; 74 | 75 | export default nodeController; 76 | -------------------------------------------------------------------------------- /server/controllers/podController.ts: -------------------------------------------------------------------------------- 1 | import { start, end, PodController, axios } from '../../types'; 2 | 3 | const podController: PodController = { 4 | 5 | // node list queries this to populate instant metrics next to names 6 | getInstantMetrics: async (req, res, next) => { 7 | const { namespace } = req.query; 8 | try { 9 | const responseMem = await axios.get( 10 | `http://localhost:9090/api/v1/query?query=container_memory_usage_bytes{namespace='${namespace}'}` 11 | ); 12 | const responseCpu = await axios.get( 13 | `http://localhost:9090/api/v1/query?query=rate(container_cpu_usage_seconds_total{namespace='${namespace}'}[2h])` 14 | ); 15 | res.locals.data = { 16 | mem: responseMem.data.data.result, 17 | cpu: responseCpu.data.data.result, 18 | }; 19 | return next(); 20 | } catch (err) { 21 | return next({ 22 | log: 'Error in podController.getInstantMetrics middleware', 23 | status: 500, 24 | message: { err: 'An error occurred' }, 25 | }); 26 | } 27 | }, 28 | 29 | // pod display makes the following queries to display the preset metrics 30 | getCpuUsage: async (req, res, next) => { 31 | const { pod } = req.query; 32 | try { 33 | const data = await axios.get( 34 | `http://localhost:9090/api/v1/query_range?query=rate(container_cpu_usage_seconds_total{pod='${pod}'}[10m])*100&start=${start}&end=${end}&step=10m` 35 | ); 36 | res.locals.cpuUsage = data; 37 | return next(); 38 | } catch (err) { 39 | return next({ 40 | log: `Error in podController.getCpuUsage: ${err}`, 41 | status: 500, 42 | message: { 43 | err: 'Error occured while retrieving pod cpu usage data', 44 | }, 45 | }); 46 | } 47 | }, 48 | 49 | getMemUsage: async (req, res, next) => { 50 | const { pod } = req.query; 51 | try { 52 | const data = await axios.get( 53 | `http://localhost:9090/api/v1/query_range?query=container_memory_usage_bytes{pod='${pod}'}&start=${start}&end=${end}&step=10m` 54 | ); 55 | res.locals.memUsage = data; 56 | return next(); 57 | } catch (err) { 58 | return next({ 59 | log: `Error in podController.getMemUsage: ${err}`, 60 | status: 500, 61 | message: { 62 | err: 'Error occured while retrieving pod memory usage data', 63 | }, 64 | }); 65 | } 66 | }, 67 | 68 | }; 69 | 70 | export default podController; 71 | -------------------------------------------------------------------------------- /server/routers/clusterRouter.ts: -------------------------------------------------------------------------------- 1 | import { express } from '../../types'; 2 | import { Request, Response } from 'express'; 3 | import clusterController from '../controllers/clusterController'; 4 | const clusterRouter = express.Router(); 5 | 6 | clusterRouter.get( 7 | '/namespaces', 8 | clusterController.getNamespaces, 9 | (req: Request, res: Response) => { 10 | return res.status(200).json(res.locals.namespaces); 11 | } 12 | ); 13 | 14 | clusterRouter.get( 15 | '/pods', 16 | clusterController.getPodsByNamespace, 17 | (req: Request, res: Response) => { 18 | return res.status(200).json(res.locals.pods); 19 | } 20 | ); 21 | 22 | clusterRouter.get( 23 | '/nodes', 24 | clusterController.getNodes, 25 | (req: Request, res: Response) => { 26 | return res.status(200).json(res.locals.nodes); 27 | } 28 | ); 29 | 30 | export default clusterRouter; 31 | -------------------------------------------------------------------------------- /server/routers/customRouter.ts: -------------------------------------------------------------------------------- 1 | import { express } from '../../types'; 2 | import { Request, Response } from 'express'; 3 | import customController from '../controllers/customController'; 4 | const customRouter = express.Router(); 5 | 6 | customRouter.post( 7 | '/test', 8 | customController.testCustomRoute, 9 | (req: Request, res: Response) => { 10 | return res.status(200).json(res.locals.valid); 11 | } 12 | ); 13 | 14 | customRouter.post( 15 | '/queries', 16 | customController.testCustomRoute, 17 | customController.addCustomRoute, 18 | (req: Request, res: Response) => { 19 | const status = res.locals.addedRoute ? 200 : 400; 20 | return res.status(status).json(res.locals.addedRoute); 21 | } 22 | ); 23 | 24 | customRouter.get( 25 | '/queries', 26 | customController.getCustomRoute, 27 | (req: Request, res: Response) => { 28 | return res.status(200).json(res.locals.data); 29 | } 30 | ); 31 | 32 | customRouter.get( 33 | '/list', 34 | customController.listCustomRoutes, 35 | (req: Request, res: Response) => { 36 | return res.status(200).json(res.locals.data); 37 | } 38 | ); 39 | 40 | customRouter.delete( 41 | '/queries', 42 | customController.deleteCustomRoute, 43 | (req: Request, res: Response) => { 44 | const status = res.locals.deletedRoute ? 200 : 400; 45 | return res.status(status).json(res.locals.route); 46 | } 47 | ); 48 | 49 | customRouter.post( 50 | '/active', 51 | customController.changeRouteActive, 52 | (req: Request, res: Response) => { 53 | return res 54 | .status(200) 55 | .send(`Query ${req.body.id} set to ${req.body.active}`); 56 | } 57 | ); 58 | 59 | export default customRouter; 60 | -------------------------------------------------------------------------------- /server/routers/dashboardRouter.ts: -------------------------------------------------------------------------------- 1 | import { express } from '../../types'; 2 | import { Request, Response } from 'express'; 3 | import dashboardController from '../controllers/dashboardController'; 4 | const dashboardRouter = express.Router(); 5 | 6 | dashboardRouter.get( 7 | '/num', 8 | dashboardController.getNumberOf, 9 | (req: Request, res: Response) => { 10 | return res.status(200).send(res.locals.data); 11 | } 12 | ); 13 | 14 | dashboardRouter.get( 15 | '/general', 16 | dashboardController.getGeneralClusterInfo, 17 | (req: Request, res: Response) => { 18 | return res.status(200).send(res.locals.data); 19 | } 20 | ); 21 | 22 | dashboardRouter.get( 23 | '/mem', 24 | dashboardController.getTotalMem, 25 | (req: Request, res: Response) => { 26 | return res.status(200).send(res.locals.totalMem.data); 27 | } 28 | ); 29 | 30 | dashboardRouter.get( 31 | '/cpu', 32 | dashboardController.getTotalCpu, 33 | (req: Request, res: Response) => { 34 | return res.status(200).send(res.locals.totalCpu.data); 35 | } 36 | ); 37 | 38 | dashboardRouter.get( 39 | '/transmit', 40 | dashboardController.getTotalTransmit, 41 | (req: Request, res: Response) => { 42 | return res.status(200).send(res.locals.totalTransmit.data); 43 | } 44 | ); 45 | 46 | dashboardRouter.get( 47 | '/receive', 48 | dashboardController.getTotalReceive, 49 | (req: Request, res: Response) => { 50 | return res.status(200).send(res.locals.totalReceive.data); 51 | } 52 | ); 53 | 54 | export default dashboardRouter; 55 | -------------------------------------------------------------------------------- /server/routers/hierarchyRouter.ts: -------------------------------------------------------------------------------- 1 | import { express } from '../../types'; 2 | import { Request, Response } from 'express'; 3 | import hierarchyController from '../controllers/hierarchyController'; 4 | const hierarchyRouter = express.Router(); 5 | 6 | hierarchyRouter.get( 7 | '/', 8 | hierarchyController.getElements, 9 | (req: Request, res: Response) => { 10 | return res.status(200).json(res.locals.elements); 11 | } 12 | ); 13 | 14 | export default hierarchyRouter; 15 | -------------------------------------------------------------------------------- /server/routers/nodeRouter.ts: -------------------------------------------------------------------------------- 1 | import { express } from '../../types'; 2 | import { Request, Response } from 'express'; 3 | import nodeController from '../controllers/nodeController'; 4 | const nodeRouter = express.Router(); 5 | 6 | nodeRouter.get( 7 | '/receive', 8 | nodeController.getNetworkReceiveBytes, 9 | (req: Request, res: Response) => { 10 | return res.status(200).json(res.locals.receiveBytes.data); 11 | } 12 | ); 13 | 14 | nodeRouter.get( 15 | '/transmit', 16 | nodeController.getNetworkTransmitBytes, 17 | (req: Request, res: Response) => { 18 | return res.status(200).json(res.locals.transmitBytes.data); 19 | } 20 | ); 21 | 22 | nodeRouter.get( 23 | '/instant', 24 | nodeController.getInstantMetrics, 25 | (req: Request, res: Response) => { 26 | return res.status(200).json(res.locals.data); 27 | } 28 | ); 29 | 30 | export default nodeRouter; 31 | -------------------------------------------------------------------------------- /server/routers/podRouter.ts: -------------------------------------------------------------------------------- 1 | import { express } from '../../types'; 2 | import { Request, Response } from 'express'; 3 | import podController from '../controllers/podController'; 4 | const podRouter = express.Router(); 5 | 6 | podRouter.get( 7 | '/cpu', 8 | podController.getCpuUsage, 9 | (req: Request, res: Response) => { 10 | return res.status(200).json(res.locals.cpuUsage.data); 11 | } 12 | ); 13 | 14 | podRouter.get( 15 | '/mem', 16 | podController.getMemUsage, 17 | (req: Request, res: Response) => { 18 | return res.status(200).json(res.locals.memUsage.data); 19 | } 20 | ); 21 | 22 | podRouter.get( 23 | '/instant', 24 | podController.getInstantMetrics, 25 | (req: Request, res: Response) => { 26 | return res.status(200).json(res.locals.data); 27 | } 28 | ); 29 | 30 | export default podRouter; 31 | -------------------------------------------------------------------------------- /server/server.ts: -------------------------------------------------------------------------------- 1 | import { ErrObject, express } from '../types'; 2 | import { Request, Response, NextFunction } from 'express'; 3 | import cors from 'cors'; 4 | import dashboardRouter from './routers/dashboardRouter'; 5 | import clusterRouter from './routers/clusterRouter'; 6 | import podRouter from './routers/podRouter'; 7 | import nodeRouter from './routers/nodeRouter'; 8 | import customRouter from './routers/customRouter'; 9 | import hierarchyRouter from './routers/hierarchyRouter'; 10 | const app = express(); 11 | 12 | app.use(cors()); 13 | app.use(express.json()); 14 | app.use(express.urlencoded({ extended: true })); 15 | 16 | app.use('/api/dashboard', dashboardRouter); 17 | app.use('/api/cluster', clusterRouter); 18 | app.use('/api/pod', podRouter); 19 | app.use('/api/node', nodeRouter); 20 | app.use('/api/custom', customRouter); 21 | app.use('/api/hierarchy', hierarchyRouter); 22 | 23 | app.use('*', (req: Request, res: Response) => 24 | res.status(404).send('404 Page Not Found') 25 | ); 26 | 27 | app.use((err: ErrObject, req: Request, res: Response) => { 28 | const defaultErr = { 29 | log: 'Express error handler caught unknown middleware error', 30 | status: 500, 31 | message: { err: 'An error occurred' }, 32 | }; 33 | const errorObj = Object.assign({}, defaultErr, err); 34 | console.log(errorObj.log); 35 | return res.status(errorObj.status).json(errorObj.message); 36 | }); 37 | 38 | app.listen(3000, () => console.log('listening on port 3000')); 39 | 40 | export default app; 41 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "ES6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | "jsx": "react" /* Specify what JSX code is generated. */, 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs" /* Specify what module code is generated. */, 29 | // "rootDir": "./", /* Specify the root folder within your source files. */ 30 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "resolveJsonModule": true, /* Enable importing .json files. */ 39 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 40 | 41 | /* JavaScript Support */ 42 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 43 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 44 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 45 | 46 | /* Emit */ 47 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 48 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 49 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 50 | "sourceMap": true /* Create source map files for emitted JavaScript files. */, 51 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 52 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 53 | "removeComments": true /* Disable emitting comments. */, 54 | // "noEmit": true, /* Disable emitting files from a compilation. */ 55 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 56 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 57 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 58 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 59 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 60 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 61 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 62 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 63 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 64 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 65 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 66 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 67 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 68 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 69 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 70 | 71 | /* Interop Constraints */ 72 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 73 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 74 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 75 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 76 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 77 | 78 | /* Type Checking */ 79 | "strict": true /* Enable all strict type-checking options. */, 80 | "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */, 81 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 82 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 83 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 84 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 85 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 86 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 87 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 88 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 89 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 90 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 91 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 92 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 93 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 94 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 95 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 96 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 97 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 98 | 99 | /* Completeness */ 100 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 101 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 102 | }, 103 | "include": ["server/**/*", "client/**/*"], 104 | "esclude": ["node_modules"] 105 | } 106 | -------------------------------------------------------------------------------- /types.ts: -------------------------------------------------------------------------------- 1 | import { RequestHandler } from 'express-serve-static-core'; 2 | export const client = require('prom-client'); 3 | export const express = require('express'); 4 | export const axios = require('axios'); 5 | export const k8s = require('@kubernetes/client-node'); 6 | export const start = new Date(Date.now() - 1440 * 60000).toISOString(); 7 | export const end = new Date(Date.now()).toISOString(); 8 | export type NodeController = { 9 | getInstantMetrics: RequestHandler; 10 | getNetworkTransmitBytes: RequestHandler; 11 | getNetworkReceiveBytes: RequestHandler; 12 | }; 13 | export type ClusterController = { 14 | getNamespaces: RequestHandler; 15 | getPodsByNamespace: RequestHandler; 16 | getNodes: RequestHandler; 17 | }; 18 | export type DashboardController = { 19 | getNumberOf: RequestHandler; 20 | getGeneralClusterInfo: RequestHandler; 21 | getTotalMem: RequestHandler; 22 | getTotalCpu: RequestHandler; 23 | getTotalTransmit: RequestHandler; 24 | getTotalReceive: RequestHandler; 25 | }; 26 | export type CustomQuery = { 27 | query: string; 28 | name: string; 29 | yAxisType: string; 30 | active: boolean; 31 | }; 32 | export type CustomController = { 33 | customClusterQueries: CustomQuery[]; 34 | customNodeQueries: CustomQuery[]; 35 | customPodQueries: CustomQuery[]; 36 | testCustomRoute: RequestHandler; 37 | addCustomRoute: RequestHandler; 38 | getCustomRoute: RequestHandler; 39 | listCustomRoutes: RequestHandler; 40 | deleteCustomRoute: RequestHandler; 41 | changeRouteActive: RequestHandler; 42 | }; 43 | export type NumOfData = { 44 | nodes: number; 45 | pods: number; 46 | namespaces: number; 47 | deployments: number; 48 | ingresses: number; 49 | services: number; 50 | }; 51 | export type GeneralData = { 52 | totalUserCpu: number; 53 | totalSystemCpu: number; 54 | totalUserSystemCpu: number; 55 | residentMemBytes: number; 56 | eventLoopLag: number; 57 | totalActiveResources: number; 58 | totalActiveHandles: number; 59 | totalActiveRequests: number; 60 | heapSizeBytes: number; 61 | heapSizeUsed: number; 62 | }; 63 | export type PodController = { 64 | getCpuUsage: RequestHandler; 65 | getMemUsage: RequestHandler; 66 | getInstantMetrics: RequestHandler; 67 | }; 68 | export type HierarchyController = { 69 | getElements: RequestHandler; 70 | }; 71 | export type ErrObject = { 72 | log: string; 73 | status: number; 74 | message: { err: string }; 75 | }; 76 | export type Elements = { 77 | data: { 78 | id?: string; 79 | label?: string; 80 | source?: string; 81 | target?: string; 82 | type?: string; 83 | }; 84 | position?: { 85 | x: number; 86 | y: number; 87 | }; 88 | }; 89 | -------------------------------------------------------------------------------- /webpack.config.ts: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | const CopyPlugin = require('copy-webpack-plugin'); 4 | 5 | module.exports = { 6 | mode: 'development', 7 | entry: './client/index.tsx', 8 | output: { 9 | path: path.resolve(__dirname, 'dist'), 10 | filename: 'bundle.js', 11 | publicPath: '/', 12 | }, 13 | module: { 14 | rules: [ 15 | { 16 | test: /\.(js|jsx)$/, 17 | exclude: /node_modules/, 18 | use: ['babel-loader'], 19 | }, 20 | { 21 | test: /\.(ts|tsx)$/, 22 | exclude: /node_modules/, 23 | use: ['ts-loader'], 24 | }, 25 | { 26 | test: /\.s?css$/, 27 | use: ['style-loader', 'css-loader', 'postcss-loader'], 28 | }, 29 | ], 30 | }, 31 | resolve: { 32 | extensions: ['.jsx', '.js', '.tsx', '.ts'], 33 | }, 34 | plugins: [ 35 | new HtmlWebpackPlugin({ 36 | template: './client/index.html', 37 | filename: './index.html', 38 | favicon: './client/favicon.ico', 39 | }), 40 | new CopyPlugin({ 41 | patterns: [{ from: './client/style.css' }], 42 | }), 43 | ], 44 | devServer: { 45 | static: { 46 | directory: path.join(__dirname, './dist'), 47 | publicPath: '/', 48 | }, 49 | proxy: { 50 | '/api': 'http://localhost:3000', 51 | secure: false, 52 | }, 53 | compress: false, 54 | host: 'localhost', 55 | port: 8080, 56 | hot: true, 57 | historyApiFallback: true, 58 | }, 59 | }; 60 | --------------------------------------------------------------------------------