├── .dockerignore ├── .gitattributes ├── .github └── workflows │ ├── codeql-analysis.yml │ └── dotnet.yml ├── .gitignore ├── LICENSE ├── README.md ├── SECURITY.md ├── UptimeKumaRemoteProbe.sln ├── docker-compose.yml └── src ├── UKRP.AppHost ├── Program.cs ├── Properties │ └── launchSettings.json ├── UKRP.AppHost.csproj ├── appsettings.Development.json └── appsettings.json ├── UKRP.ServiceDefaults ├── Extensions.cs └── UKRP.ServiceDefaults.csproj └── UptimeKumaRemoteProbe ├── Data └── ApplicationDbContext.cs ├── Dockerfile ├── Dockerfile.multiarch ├── GlobalSuppressions.cs ├── GlobalUsings.cs ├── Models ├── AppSettings.cs ├── Configurations.cs ├── DbVersion.cs ├── Domain.cs └── Monitors.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Services ├── CertificateService.cs ├── DbService.cs ├── DomainService.cs ├── HealthCheckPublisher.cs ├── HttpService.cs ├── MonitorsService.cs ├── PingService.cs ├── PushService.cs ├── TcpService.cs └── VersionService.cs ├── UptimeKumaRemoteProbe.csproj ├── Worker.cs ├── appsettings.Development.json ├── appsettings.json ├── health └── uptime-kuma.ico /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL Advanced" 13 | 14 | on: 15 | push: 16 | branches: [ "main" ] 17 | pull_request: 18 | branches: [ "main" ] 19 | 20 | 21 | jobs: 22 | analyze: 23 | name: Analyze (${{ matrix.language }}) 24 | # Runner size impacts CodeQL analysis time. To learn more, please see: 25 | # - https://gh.io/recommended-hardware-resources-for-running-codeql 26 | # - https://gh.io/supported-runners-and-hardware-resources 27 | # - https://gh.io/using-larger-runners (GitHub.com only) 28 | # Consider using larger runners or machines with greater resources for possible analysis time improvements. 29 | runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} 30 | permissions: 31 | # required for all workflows 32 | security-events: write 33 | 34 | # required to fetch internal or private CodeQL packs 35 | packages: read 36 | 37 | # only required for workflows in private repositories 38 | actions: read 39 | contents: read 40 | 41 | strategy: 42 | fail-fast: false 43 | matrix: 44 | include: 45 | - language: actions 46 | build-mode: none 47 | - language: csharp 48 | build-mode: none 49 | # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' 50 | # Use `c-cpp` to analyze code written in C, C++ or both 51 | # Use 'java-kotlin' to analyze code written in Java, Kotlin or both 52 | # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both 53 | # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, 54 | # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. 55 | # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how 56 | # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages 57 | steps: 58 | - name: Checkout repository 59 | uses: actions/checkout@v4 60 | 61 | # Add any setup steps before running the `github/codeql-action/init` action. 62 | # This includes steps like installing compilers or runtimes (`actions/setup-node` 63 | # or others). This is typically only required for manual builds. 64 | # - name: Setup runtime (example) 65 | # uses: actions/setup-example@v1 66 | 67 | # Initializes the CodeQL tools for scanning. 68 | - name: Initialize CodeQL 69 | uses: github/codeql-action/init@v3 70 | with: 71 | languages: ${{ matrix.language }} 72 | build-mode: ${{ matrix.build-mode }} 73 | # If you wish to specify custom queries, you can do so here or in a config file. 74 | # By default, queries listed here will override any specified in a config file. 75 | # Prefix the list here with "+" to use these queries and those in the config file. 76 | 77 | # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 78 | # queries: security-extended,security-and-quality 79 | 80 | # If the analyze step fails for one of the languages you are analyzing with 81 | # "We were unable to automatically build your code", modify the matrix above 82 | # to set the build mode to "manual" for that language. Then modify this step 83 | # to build your code. 84 | # ℹ️ Command-line programs to run using the OS shell. 85 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 86 | - if: matrix.build-mode == 'manual' 87 | shell: bash 88 | run: | 89 | echo 'If you are using a "manual" build mode for one or more of the' \ 90 | 'languages you are analyzing, replace this with the commands to build' \ 91 | 'your code, for example:' 92 | echo ' make bootstrap' 93 | echo ' make release' 94 | exit 1 95 | 96 | - name: Perform CodeQL Analysis 97 | uses: github/codeql-action/analyze@v3 98 | with: 99 | category: "/language:${{matrix.language}}" -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | release: 9 | name: Release 10 | strategy: 11 | matrix: 12 | kind: ['linux', 'linux-arm', 'linux-arm64', 'windows', 'macOS'] 13 | include: 14 | - kind: linux 15 | os: ubuntu-latest 16 | target: linux-x64 17 | - kind: linux-arm 18 | os: ubuntu-latest 19 | target: linux-arm 20 | - kind: linux-arm64 21 | os: ubuntu-latest 22 | target: linux-arm64 23 | - kind: windows 24 | os: windows-latest 25 | target: win-x64 26 | - kind: macOS 27 | os: macos-latest 28 | target: osx-x64 29 | runs-on: ${{ matrix.os }} 30 | steps: 31 | - name: Checkout 32 | uses: actions/checkout@v4 33 | 34 | - name: Setup dotnet 35 | uses: actions/setup-dotnet@v4 36 | with: 37 | dotnet-version: 9.0.x 38 | 39 | - name: Build 40 | shell: bash 41 | run: | 42 | tag=$(git describe --tags --abbrev=0) 43 | release_name="UptimeKumaRemoteProbe-$tag-${{ matrix.target }}" 44 | 45 | dotnet publish src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj --framework net9.0 --runtime "${{ matrix.target }}" --no-self-contained -p:PublishSingleFile=true -c Release -o "$release_name" 46 | 47 | if [ "${{ matrix.target }}" == "win-x64" ]; then 48 | 7z a -tzip "${release_name}.zip" "./${release_name}/*" 49 | else 50 | tar czvf "${release_name}.tar.gz" "$release_name" 51 | fi 52 | 53 | rm -r "$release_name" 54 | 55 | - name: Publish 56 | uses: softprops/action-gh-release@v2 57 | with: 58 | files: "UptimeKumaRemoteProbe-*" 59 | 60 | env: 61 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 62 | 63 | build: 64 | name: Build image 65 | runs-on: ubuntu-latest 66 | steps: 67 | - name: Docker meta 68 | id: meta 69 | uses: docker/metadata-action@v5 70 | with: 71 | images: | 72 | zimbres/uptime-kuma-remote-probe 73 | flavor: | 74 | latest=true 75 | tags: | 76 | type=ref,event=tag 77 | 78 | - name: Checkout 79 | uses: actions/checkout@v4 80 | 81 | - name: Set up QEMU 82 | uses: docker/setup-qemu-action@v3 83 | 84 | - name: Set up Docker Buildx 85 | uses: docker/setup-buildx-action@v3 86 | 87 | - name: Login to container registry 88 | uses: docker/login-action@v3 89 | with: 90 | username: ${{ secrets.DOCKERHUB_USERNAME }} 91 | password: ${{ secrets.DOCKERHUB_TOKEN }} 92 | registry: docker.io 93 | 94 | - name: Build and Push Image 95 | uses: docker/build-push-action@v5 96 | with: 97 | context: . 98 | file: src/UptimeKumaRemoteProbe/Dockerfile.multiarch 99 | tags: ${{ steps.meta.outputs.tags }} 100 | platforms: linux/amd64,linux/arm64,linux/arm/v7 101 | push: true 102 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 zimbres 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Publish](https://github.com/zimbres/UptimeKumaRemoteProbe/actions/workflows/dotnet.yml/badge.svg?event=release)](https://github.com/zimbres/UptimeKumaRemoteProbe/actions/workflows/dotnet.yml) [![.CodeQL](https://github.com/zimbres/UptimeKumaRemoteProbe/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/zimbres/UptimeKumaRemoteProbe/actions/workflows/codeql-analysis.yml) 2 | 3 | 4 | # Uptime Kuma Remote Probe / Push Agent 5 | 6 | >Uptime Kuma repository https://github.com/louislam/uptime-kuma 7 | 8 | --- 9 | 10 | ### Pre built container 11 | 12 | >https://hub.docker.com/r/zimbres/uptime-kuma-remote-probe 13 | 14 | 15 | --- 16 | 17 | Services configuration is done by editing the file appsettings.json and restarting application. 18 | 19 | `"UpDependency": "192.168.1.1"` should be a trustable IP in your network, your ISP gateway for example. In case of this IP is not available, no other checks will be executed. 20 | 21 | `"Delay": 60000` is the delay time between checks. It is expressed in milliseconds, in this example 1 minute between each round. 22 | 23 | --- 24 | 25 | **Please Note** : From version > 3.0 the services configuration is not done by adding it to appsettings.json, services to be executed on the probe will be auto discovered by tags set in UK. 26 | 27 | Username and Password for UK need to be set on appsettings.json "Configurations.Username/Password" also UK Url. Account with 2FA is not supported. 28 | 29 | Ex: 30 | 31 | - Tag Name: "Probe" / Tag Value: "House" -> This value also must be set in appsettings.json on field "Configurations.ProbeName" 32 | - Tag Name: "Type" / Tag Value: "Ping" 33 | - Tag Name: "Address" / Tag Value: "1.1.1.1" 34 | - Tag Name: "Domain" / Tag Value: "domain.com" 35 | - Tag Name: "Method" / Tag Value: "GET" 36 | - Tag Name: "CertificateExpiration" / Tag Value: "7" 37 | - Tag Name: "IgnoreSSL" / Tag Value: "False" 38 | 39 | ![image](https://github.com/zimbres/UptimeKumaRemoteProbe/assets/29772043/a4a9fd07-4f33-4f4f-9c27-24b59be42b28) 40 | 41 | --- 42 | Available monitors type are: 43 | 44 | - Ping 45 | - Http, with or whithout Keyword. Tag Name "Keyword" must be applied to also check this 46 | - Tcp 47 | - Certificate 48 | - Database 49 | - Domain 50 | 51 | `Tags and Values are case sensitive.` 52 | 53 | Service for Domain check is [Whois Json](https://whoisjson.com/). You need an account and replace the "WhoisApiToken" field with your token on appsettings.json. 54 | 55 | This service has a api call limit of 500 per month, this would be enough since this check will run once a day only, or at the probe restart. 56 | 57 | By default if the domain expiration date is < 30 days, probe will not push to UK and generate an alert. 58 | 59 | --- 60 | 61 | Pré compiled package is available for Windows and Linux. It requires .Net Runtime 9.x. 62 | 63 | [Download .NET 9.0](https://dotnet.microsoft.com/en-us/download/dotnet/9.0) 64 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ---------- | ------------------ | 7 | | >= 7.0.0.1 | :white_check_mark: | 8 | | = 1.0.1.4 | :x: | 9 | 10 | 11 | ## Reporting a Vulnerability 12 | 13 | Create a new issue 14 | -------------------------------------------------------------------------------- /UptimeKumaRemoteProbe.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34309.116 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4A42D506-96D1-4492-92DB-35B8013122A8}" 7 | ProjectSection(SolutionItems) = preProject 8 | .github\workflows\codeql-analysis.yml = .github\workflows\codeql-analysis.yml 9 | docker-compose.yml = docker-compose.yml 10 | .github\workflows\dotnet.yml = .github\workflows\dotnet.yml 11 | LICENSE = LICENSE 12 | README.md = README.md 13 | SECURITY.md = SECURITY.md 14 | EndProjectSection 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UptimeKumaRemoteProbe", "src\UptimeKumaRemoteProbe\UptimeKumaRemoteProbe.csproj", "{291D4A53-0E98-4E7B-861D-C43973C0B5D1}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UKRP.AppHost", "src\UKRP.AppHost\UKRP.AppHost.csproj", "{07875E62-655F-44E9-8781-1F24DB832BA1}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UKRP.ServiceDefaults", "src\UKRP.ServiceDefaults\UKRP.ServiceDefaults.csproj", "{03B064F8-A9A3-4380-9F77-2D025C51185E}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Aspire", "Aspire", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {291D4A53-0E98-4E7B-861D-C43973C0B5D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {291D4A53-0E98-4E7B-861D-C43973C0B5D1}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {291D4A53-0E98-4E7B-861D-C43973C0B5D1}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {291D4A53-0E98-4E7B-861D-C43973C0B5D1}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {07875E62-655F-44E9-8781-1F24DB832BA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {07875E62-655F-44E9-8781-1F24DB832BA1}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {07875E62-655F-44E9-8781-1F24DB832BA1}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {07875E62-655F-44E9-8781-1F24DB832BA1}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {03B064F8-A9A3-4380-9F77-2D025C51185E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {03B064F8-A9A3-4380-9F77-2D025C51185E}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {03B064F8-A9A3-4380-9F77-2D025C51185E}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {03B064F8-A9A3-4380-9F77-2D025C51185E}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(NestedProjects) = preSolution 47 | {07875E62-655F-44E9-8781-1F24DB832BA1} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} 48 | {03B064F8-A9A3-4380-9F77-2D025C51185E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} 49 | EndGlobalSection 50 | GlobalSection(ExtensibilityGlobals) = postSolution 51 | SolutionGuid = {2C2CAF34-25CA-44E6-87B1-6A36456595FB} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.9' 2 | 3 | services: 4 | worker: 5 | build: 6 | context: ./src/UptimeKumaRemoteProbe 7 | dockerfile: Dockerfile 8 | -------------------------------------------------------------------------------- /src/UKRP.AppHost/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = DistributedApplication.CreateBuilder(args); 2 | 3 | builder.AddProject("uptimekumaremoteprobe"); 4 | 5 | builder.Build().Run(); 6 | -------------------------------------------------------------------------------- /src/UKRP.AppHost/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "https": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": true, 8 | "applicationUrl": "https://localhost:17047;http://localhost:15113", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development", 11 | "DOTNET_ENVIRONMENT": "Development", 12 | "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21296", 13 | "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22162" 14 | } 15 | }, 16 | "http": { 17 | "commandName": "Project", 18 | "dotnetRunMessages": true, 19 | "launchBrowser": true, 20 | "applicationUrl": "http://localhost:15113", 21 | "environmentVariables": { 22 | "ASPNETCORE_ENVIRONMENT": "Development", 23 | "DOTNET_ENVIRONMENT": "Development", 24 | "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19132", 25 | "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20111", 26 | "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/UKRP.AppHost/UKRP.AppHost.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Exe 7 | net8.0 8 | enable 9 | enable 10 | true 11 | 9b25896d-67a2-4379-9411-47b0e205791d 12 | $(PackageVersion) 13 | $(PackageVersion) 14 | 1.0.0.0 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/UKRP.AppHost/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/UKRP.AppHost/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning", 6 | "Aspire.Hosting.Dcp": "Warning" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/UKRP.ServiceDefaults/Extensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Diagnostics.HealthChecks; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Diagnostics.HealthChecks; 5 | using Microsoft.Extensions.Logging; 6 | using OpenTelemetry; 7 | using OpenTelemetry.Metrics; 8 | using OpenTelemetry.Trace; 9 | 10 | namespace Microsoft.Extensions.Hosting; 11 | 12 | // Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry. 13 | // This project should be referenced by each service project in your solution. 14 | // To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults 15 | public static class Extensions 16 | { 17 | public static TBuilder AddServiceDefaults(this TBuilder builder) where TBuilder : IHostApplicationBuilder 18 | { 19 | builder.ConfigureOpenTelemetry(); 20 | 21 | builder.AddDefaultHealthChecks(); 22 | 23 | builder.Services.AddServiceDiscovery(); 24 | 25 | builder.Services.ConfigureHttpClientDefaults(http => 26 | { 27 | // Turn on resilience by default 28 | http.AddStandardResilienceHandler(); 29 | 30 | // Turn on service discovery by default 31 | http.AddServiceDiscovery(); 32 | }); 33 | 34 | // Uncomment the following to restrict the allowed schemes for service discovery. 35 | // builder.Services.Configure(options => 36 | // { 37 | // options.AllowedSchemes = ["https"]; 38 | // }); 39 | 40 | return builder; 41 | } 42 | 43 | public static TBuilder ConfigureOpenTelemetry(this TBuilder builder) where TBuilder : IHostApplicationBuilder 44 | { 45 | builder.Logging.AddOpenTelemetry(logging => 46 | { 47 | logging.IncludeFormattedMessage = true; 48 | logging.IncludeScopes = true; 49 | }); 50 | 51 | builder.Services.AddOpenTelemetry() 52 | .WithMetrics(metrics => 53 | { 54 | metrics.AddAspNetCoreInstrumentation() 55 | .AddHttpClientInstrumentation() 56 | .AddRuntimeInstrumentation(); 57 | }) 58 | .WithTracing(tracing => 59 | { 60 | tracing.AddSource(builder.Environment.ApplicationName) 61 | .AddAspNetCoreInstrumentation() 62 | // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package) 63 | //.AddGrpcClientInstrumentation() 64 | .AddHttpClientInstrumentation(); 65 | }); 66 | 67 | builder.AddOpenTelemetryExporters(); 68 | 69 | return builder; 70 | } 71 | 72 | private static TBuilder AddOpenTelemetryExporters(this TBuilder builder) where TBuilder : IHostApplicationBuilder 73 | { 74 | var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]); 75 | 76 | if (useOtlpExporter) 77 | { 78 | builder.Services.AddOpenTelemetry().UseOtlpExporter(); 79 | } 80 | 81 | // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package) 82 | //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"])) 83 | //{ 84 | // builder.Services.AddOpenTelemetry() 85 | // .UseAzureMonitor(); 86 | //} 87 | 88 | return builder; 89 | } 90 | 91 | public static TBuilder AddDefaultHealthChecks(this TBuilder builder) where TBuilder : IHostApplicationBuilder 92 | { 93 | builder.Services.AddHealthChecks() 94 | // Add a default liveness check to ensure app is responsive 95 | .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]); 96 | 97 | return builder; 98 | } 99 | 100 | public static WebApplication MapDefaultEndpoints(this WebApplication app) 101 | { 102 | // Adding health checks endpoints to applications in non-development environments has security implications. 103 | // See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments. 104 | if (app.Environment.IsDevelopment()) 105 | { 106 | // All health checks must pass for app to be considered ready to accept traffic after starting 107 | app.MapHealthChecks("/health"); 108 | 109 | // Only health checks tagged with the "live" tag must pass for app to be considered alive 110 | app.MapHealthChecks("/alive", new HealthCheckOptions 111 | { 112 | Predicate = r => r.Tags.Contains("live") 113 | }); 114 | } 115 | 116 | return app; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/UKRP.ServiceDefaults/UKRP.ServiceDefaults.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | true 8 | $(PackageVersion) 9 | $(PackageVersion) 10 | 1.0.0.0 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Data/ApplicationDbContext.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Data; 2 | 3 | public class ApplicationDbContext : DbContext 4 | { 5 | private readonly Endpoint _endpoint; 6 | 7 | public ApplicationDbContext(Endpoint endpoint) 8 | { 9 | _endpoint = endpoint; 10 | } 11 | 12 | public DbSet DbVersion { get; set; } 13 | 14 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 15 | { 16 | switch (_endpoint.Brand) 17 | { 18 | case "MSSQL": 19 | optionsBuilder.UseSqlServer(_endpoint.ConnectionString); 20 | break; 21 | case "MYSQL": 22 | optionsBuilder.UseMySQL(_endpoint.ConnectionString); 23 | break; 24 | case "PGSQL": 25 | optionsBuilder.UseNpgsql(_endpoint.ConnectionString); 26 | break; 27 | default: 28 | break; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base 4 | RUN apt-get update && apt-get install -y --no-install-recommends \ 5 | iputils-ping \ 6 | && rm -rf /var/lib/apt/lists/* 7 | RUN chmod u+s /bin/ping 8 | USER $APP_UID 9 | WORKDIR /app 10 | 11 | FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build 12 | WORKDIR /src 13 | COPY ["src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj", "src/UptimeKumaRemoteProbe/"] 14 | RUN dotnet restore "./src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj" 15 | COPY . . 16 | WORKDIR "/src/src/UptimeKumaRemoteProbe" 17 | RUN dotnet build "./UptimeKumaRemoteProbe.csproj" -c Release -o /app/build 18 | 19 | FROM build AS publish 20 | RUN dotnet publish "./UptimeKumaRemoteProbe.csproj" -c Release -o /app/publish 21 | 22 | FROM base AS final 23 | WORKDIR /app 24 | COPY --from=publish /app/publish . 25 | ENTRYPOINT ["./UptimeKumaRemoteProbe"] -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Dockerfile.multiarch: -------------------------------------------------------------------------------- 1 | FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:9.0 AS build 2 | WORKDIR /src 3 | COPY ["src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj", "src/UptimeKumaRemoteProbe/"] 4 | RUN dotnet restore "./src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj" 5 | COPY . . 6 | 7 | ARG TARGETPLATFORM 8 | 9 | RUN if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \ 10 | RID=linux-x64 ; \ 11 | elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then \ 12 | RID=linux-arm64 ; \ 13 | elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then \ 14 | RID=linux-arm ; \ 15 | fi \ 16 | && dotnet publish "src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj" -c Release -o /app/publish -r $RID --self-contained false 17 | 18 | FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS final 19 | RUN apt-get update && apt-get install -y --no-install-recommends \ 20 | iputils-ping \ 21 | && rm -rf /var/lib/apt/lists/* 22 | RUN chmod u+s /bin/ping 23 | USER $APP_UID 24 | WORKDIR /app 25 | COPY --from=build /app/publish . 26 | 27 | ENTRYPOINT ["./UptimeKumaRemoteProbe"] -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("Usage", "VSTHRD101:Avoid unsupported async delegates", Justification = "", Scope = "member", Target = "~M:UptimeKumaRemoteProbe.Services.MonitorsService.GetMonitorsAsync~System.Threading.Tasks.Task{System.Collections.Generic.List{UptimeKumaRemoteProbe.Models.Monitors}}")] 9 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.EntityFrameworkCore; 2 | global using Microsoft.Extensions.DependencyInjection.Extensions; 3 | global using Microsoft.Extensions.Diagnostics.HealthChecks; 4 | global using Microsoft.Extensions.Http; 5 | global using System.Diagnostics; 6 | global using System.Globalization; 7 | global using System.Net.NetworkInformation; 8 | global using System.Net.Sockets; 9 | global using System.Reflection; 10 | global using System.Text.Json; 11 | global using System.Text.Json.Nodes; 12 | global using System.Text.Json.Serialization; 13 | global using UptimeKumaRemoteProbe; 14 | global using UptimeKumaRemoteProbe.Data; 15 | global using UptimeKumaRemoteProbe.Models; 16 | global using UptimeKumaRemoteProbe.Services; 17 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Models/AppSettings.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Models; 2 | 3 | public class AppSettings 4 | { 5 | private readonly Configurations _configuration; 6 | 7 | public string Url { get; set; } 8 | public string Username { get; set; } 9 | public string Password { get; set; } 10 | public string ProbeName { get; set; } 11 | public string UpDependency { get; set; } 12 | public int Timeout { get; set; } 13 | public int Delay { get; set; } 14 | public string WhoisApiUrl { get; set; } 15 | public string WhoisApiToken { get; set; } 16 | 17 | public AppSettings(IConfiguration configuration) 18 | { 19 | _configuration = configuration.GetSection(nameof(Configurations)).Get(); 20 | 21 | _ = bool.TryParse(Environment.GetEnvironmentVariable("UseEnvironmentVariables"), out bool useEnv); 22 | 23 | Url = Environment.GetEnvironmentVariable("Url") is not null && useEnv ? Environment.GetEnvironmentVariable("Url") : _configuration.Url; 24 | Username = Environment.GetEnvironmentVariable("Username") is not null && useEnv ? Environment.GetEnvironmentVariable("Username") : _configuration.Username; 25 | Password = Environment.GetEnvironmentVariable("Password") is not null && useEnv ? Environment.GetEnvironmentVariable("Password") : _configuration.Password; 26 | ProbeName = Environment.GetEnvironmentVariable("ProbeName") is not null && useEnv ? Environment.GetEnvironmentVariable("ProbeName") : _configuration.ProbeName; 27 | UpDependency = Environment.GetEnvironmentVariable("UpDependency") is not null && useEnv ? Environment.GetEnvironmentVariable("UpDependency") : _configuration.UpDependency; 28 | Timeout = Environment.GetEnvironmentVariable("Timeout") is not null && useEnv ? int.Parse(Environment.GetEnvironmentVariable("Timeout")) : _configuration.Timeout; 29 | Delay = Environment.GetEnvironmentVariable("Delay") is not null && useEnv ? int.Parse(Environment.GetEnvironmentVariable("Delay")) : _configuration.Delay; 30 | WhoisApiUrl = Environment.GetEnvironmentVariable("WhoisApiUrl") is not null && useEnv ? Environment.GetEnvironmentVariable("WhoisApiUrl") : _configuration.WhoisApiUrl; 31 | WhoisApiToken = Environment.GetEnvironmentVariable("WhoisApiToken") is not null && useEnv ? Environment.GetEnvironmentVariable("WhoisApiToken") : _configuration.WhoisApiToken; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Models/Configurations.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Models; 2 | 3 | public class Configurations 4 | { 5 | public ConnectionStrings ConnectionStrings { get; set; } 6 | public string Url { get; set; } 7 | public string Username { get; set; } 8 | public string Password { get; set; } 9 | public string ProbeName { get; set; } 10 | public string UpDependency { get; set; } 11 | public int Timeout { get; set; } 12 | public int Delay { get; set; } 13 | public string WhoisApiUrl { get; set; } 14 | public string WhoisApiToken { get; set; } 15 | } 16 | 17 | public class Endpoint 18 | { 19 | public string Type { get; set; } 20 | public Uri PushUri { get; set; } 21 | public string Destination { get; set; } 22 | public int Port { get; set; } 23 | public string Method { get; set; } 24 | public string Keyword { get; set; } 25 | public bool IgnoreSSL { get; set; } 26 | public int Timeout { get; set; } 27 | public int CertificateExpiration { get; set; } 28 | public string ConnectionString { get; set; } 29 | public string Brand { get; set; } 30 | public string Domain { get; set; } 31 | } 32 | 33 | public class ConnectionStrings 34 | { 35 | public string PGSQL { get; set; } 36 | public string MYSQL { get; set; } 37 | public string MSSQL { get; set; } 38 | } -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Models/DbVersion.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Models; 2 | 3 | [Keyless] 4 | public class DbVersion 5 | { 6 | public string Version { get; set; } 7 | } 8 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Models/Domain.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Models; 2 | 3 | public class Domain 4 | { 5 | [JsonPropertyName("server")] 6 | public string Server { get; set; } 7 | 8 | [JsonPropertyName("name")] 9 | public string Name { get; set; } 10 | 11 | [JsonPropertyName("idnName")] 12 | public string IdnName { get; set; } 13 | 14 | [JsonPropertyName("nameserver")] 15 | public string[] Nameserver { get; set; } 16 | 17 | [JsonPropertyName("ips")] 18 | public string Ips { get; set; } 19 | 20 | [JsonPropertyName("created")] 21 | public string Created { get; set; } 22 | 23 | [JsonPropertyName("changed")] 24 | public string Changed { get; set; } 25 | 26 | [JsonPropertyName("expires")] 27 | public string Expires { get; set; } 28 | 29 | [JsonPropertyName("registered")] 30 | public bool Registered { get; set; } 31 | 32 | [JsonPropertyName("whoisserver")] 33 | public string Whoisserver { get; set; } 34 | } 35 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Models/Monitors.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Models; 2 | 3 | public class Monitors 4 | { 5 | [JsonPropertyName("id")] 6 | public long Id { get; set; } 7 | 8 | [JsonPropertyName("name")] 9 | public string Name { get; set; } 10 | 11 | [JsonPropertyName("url")] 12 | public string Url { get; set; } 13 | 14 | [JsonPropertyName("method")] 15 | public string Method { get; set; } 16 | 17 | [JsonPropertyName("hostname")] 18 | public object Hostname { get; set; } 19 | 20 | [JsonPropertyName("port")] 21 | public object Port { get; set; } 22 | 23 | [JsonPropertyName("maxretries")] 24 | public long Maxretries { get; set; } 25 | 26 | [JsonPropertyName("weight")] 27 | public long Weight { get; set; } 28 | 29 | [JsonPropertyName("active")] 30 | [JsonConverter(typeof(JsonBooleanOrIntConverter))] 31 | public bool Active { get; set; } 32 | 33 | [JsonPropertyName("type")] 34 | public string Type { get; set; } 35 | 36 | [JsonPropertyName("interval")] 37 | public long Interval { get; set; } 38 | 39 | [JsonPropertyName("retryInterval")] 40 | public long RetryInterval { get; set; } 41 | 42 | [JsonPropertyName("resendInterval")] 43 | public long ResendInterval { get; set; } 44 | 45 | [JsonPropertyName("keyword")] 46 | public object Keyword { get; set; } 47 | 48 | [JsonPropertyName("expiryNotification")] 49 | public bool ExpiryNotification { get; set; } 50 | 51 | [JsonPropertyName("ignoreTls")] 52 | public bool IgnoreTls { get; set; } 53 | 54 | [JsonPropertyName("upsideDown")] 55 | public bool UpsideDown { get; set; } 56 | 57 | [JsonPropertyName("maxredirects")] 58 | public long Maxredirects { get; set; } 59 | 60 | [JsonPropertyName("accepted_statuscodes")] 61 | public string[] AcceptedStatuscodes { get; set; } 62 | 63 | [JsonPropertyName("dns_resolve_type")] 64 | public string DnsResolveType { get; set; } 65 | 66 | [JsonPropertyName("dns_resolve_server")] 67 | public string DnsResolveServer { get; set; } 68 | 69 | [JsonPropertyName("dns_last_result")] 70 | public object DnsLastResult { get; set; } 71 | 72 | [JsonPropertyName("docker_container")] 73 | public string DockerContainer { get; set; } 74 | 75 | [JsonPropertyName("docker_host")] 76 | public object DockerHost { get; set; } 77 | 78 | [JsonPropertyName("proxyId")] 79 | public object ProxyId { get; set; } 80 | 81 | [JsonPropertyName("notificationIDList")] 82 | public object NotificationIdList { get; set; } 83 | 84 | [JsonPropertyName("tags")] 85 | public Tag[] Tags { get; set; } 86 | 87 | [JsonPropertyName("maintenance")] 88 | public bool Maintenance { get; set; } 89 | 90 | [JsonPropertyName("mqttTopic")] 91 | public string MqttTopic { get; set; } 92 | 93 | [JsonPropertyName("mqttSuccessMessage")] 94 | public string MqttSuccessMessage { get; set; } 95 | 96 | [JsonPropertyName("databaseQuery")] 97 | public object DatabaseQuery { get; set; } 98 | 99 | [JsonPropertyName("authMethod")] 100 | public object AuthMethod { get; set; } 101 | 102 | [JsonPropertyName("grpcUrl")] 103 | public object GrpcUrl { get; set; } 104 | 105 | [JsonPropertyName("grpcProtobuf")] 106 | public object GrpcProtobuf { get; set; } 107 | 108 | [JsonPropertyName("grpcMethod")] 109 | public object GrpcMethod { get; set; } 110 | 111 | [JsonPropertyName("grpcServiceName")] 112 | public object GrpcServiceName { get; set; } 113 | 114 | [JsonPropertyName("grpcEnableTls")] 115 | public bool GrpcEnableTls { get; set; } 116 | 117 | [JsonPropertyName("radiusCalledStationId")] 118 | public object RadiusCalledStationId { get; set; } 119 | 120 | [JsonPropertyName("radiusCallingStationId")] 121 | public object RadiusCallingStationId { get; set; } 122 | 123 | [JsonPropertyName("headers")] 124 | public object Headers { get; set; } 125 | 126 | [JsonPropertyName("body")] 127 | public object Body { get; set; } 128 | 129 | [JsonPropertyName("grpcBody")] 130 | public object GrpcBody { get; set; } 131 | 132 | [JsonPropertyName("grpcMetadata")] 133 | public object GrpcMetadata { get; set; } 134 | 135 | [JsonPropertyName("basic_auth_user")] 136 | public object BasicAuthUser { get; set; } 137 | 138 | [JsonPropertyName("basic_auth_pass")] 139 | public object BasicAuthPass { get; set; } 140 | 141 | [JsonPropertyName("pushToken")] 142 | public string PushToken { get; set; } 143 | 144 | [JsonPropertyName("databaseConnectionString")] 145 | public object DatabaseConnectionString { get; set; } 146 | 147 | [JsonPropertyName("radiusUsername")] 148 | public object RadiusUsername { get; set; } 149 | 150 | [JsonPropertyName("radiusPassword")] 151 | public object RadiusPassword { get; set; } 152 | 153 | [JsonPropertyName("radiusSecret")] 154 | public object RadiusSecret { get; set; } 155 | 156 | [JsonPropertyName("mqttUsername")] 157 | public string MqttUsername { get; set; } 158 | 159 | [JsonPropertyName("mqttPassword")] 160 | public string MqttPassword { get; set; } 161 | 162 | [JsonPropertyName("authWorkstation")] 163 | public object AuthWorkstation { get; set; } 164 | 165 | [JsonPropertyName("authDomain")] 166 | public object AuthDomain { get; set; } 167 | 168 | [JsonPropertyName("includeSensitiveData")] 169 | public bool IncludeSensitiveData { get; set; } 170 | } 171 | 172 | public class Tag 173 | { 174 | [JsonPropertyName("id")] 175 | public long Id { get; set; } 176 | 177 | [JsonPropertyName("monitor_id")] 178 | public long MonitorId { get; set; } 179 | 180 | [JsonPropertyName("tag_id")] 181 | public long TagId { get; set; } 182 | 183 | [JsonPropertyName("value")] 184 | public string Value { get; set; } 185 | 186 | [JsonPropertyName("name")] 187 | public string Name { get; set; } 188 | 189 | [JsonPropertyName("color")] 190 | public string Color { get; set; } 191 | } 192 | 193 | public class JsonBooleanOrIntConverter : JsonConverter 194 | { 195 | public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 196 | { 197 | if (reader.TokenType == JsonTokenType.Number) 198 | { 199 | int value = reader.GetInt32(); 200 | return value != 0; 201 | } 202 | else if (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False) 203 | { 204 | return reader.GetBoolean(); 205 | } 206 | 207 | throw new JsonException("Expected boolean or 0 for false."); 208 | } 209 | 210 | public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) 211 | { 212 | writer.WriteBooleanValue(value); 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Program.cs: -------------------------------------------------------------------------------- 1 | var builder = Host.CreateApplicationBuilder(args); 2 | 3 | builder.AddServiceDefaults(); 4 | builder.Services.AddHttpClient("Default"); 5 | builder.Services.AddHttpClient("IgnoreSSL") 6 | .ConfigurePrimaryHttpMessageHandler(() => 7 | { 8 | return new HttpClientHandler 9 | { 10 | ServerCertificateCustomValidationCallback = (m, c, ch, e) => true 11 | }; 12 | }); 13 | builder.Services.AddSingleton(); 14 | builder.Services.AddSingleton(); 15 | builder.Services.AddSingleton(); 16 | builder.Services.AddSingleton(); 17 | builder.Services.AddSingleton(); 18 | builder.Services.AddSingleton(); 19 | builder.Services.AddSingleton(); 20 | builder.Services.AddSingleton(); 21 | builder.Services.AddHostedService().Configure(options => 22 | { 23 | options.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore; 24 | }); 25 | builder.Services.RemoveAll(); //Disable HttpClient Logging 26 | builder.Services.AddHealthChecks().AddCheck("HealthCheck", () => HealthCheckResult.Healthy()); 27 | builder.Services.AddSingleton(); 28 | builder.Services.Configure(options => 29 | { 30 | options.Delay = TimeSpan.FromSeconds(5); 31 | options.Period = TimeSpan.FromSeconds(20); 32 | }); 33 | builder.Services.AddSingleton(); 34 | builder.Services.AddSingleton(); 35 | 36 | var host = builder.Build(); 37 | host.Run(); 38 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "UptimeKumaRemoteProbe": { 4 | "commandName": "Project", 5 | "environmentVariables": { 6 | "DOTNET_ENVIRONMENT": "Development", 7 | "UseEnvironmentVariables": "false" 8 | }, 9 | "dotnetRunMessages": true 10 | }, 11 | "Docker": { 12 | "commandName": "Docker" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/CertificateService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class CertificateService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly PushService _pushService; 7 | private readonly IHttpClientFactory _httpClientFactory; 8 | private HttpClient _httpClient; 9 | 10 | public CertificateService(ILogger logger, PushService pushService, IHttpClientFactory httpClientFactory, HttpClient httpClient) 11 | { 12 | _logger = logger; 13 | _pushService = pushService; 14 | _httpClientFactory = httpClientFactory; 15 | _httpClient = httpClient; 16 | } 17 | 18 | public async Task CheckCertificateAsync(Endpoint endpoint) 19 | { 20 | DateTime notAfter = DateTime.UtcNow; 21 | 22 | var httpClientHandler = new HttpClientHandler 23 | { 24 | ServerCertificateCustomValidationCallback = (request, cert, chain, policyErrors) => 25 | { 26 | notAfter = cert.NotAfter; 27 | return true; 28 | } 29 | }; 30 | 31 | _httpClient = _httpClientFactory.CreateClient("IgnoreSSL"); 32 | _httpClient = new HttpClient(httpClientHandler); 33 | 34 | try 35 | { 36 | var result = await _httpClient.SendAsync(new HttpRequestMessage(new HttpMethod(endpoint.Method ?? "Head"), endpoint.Destination)); 37 | 38 | if (notAfter >= DateTime.UtcNow.AddDays(endpoint.CertificateExpiration)) 39 | { 40 | await _pushService.PushAsync(endpoint.PushUri, (notAfter - DateTime.UtcNow).Days); 41 | _logger.LogInformation("Certificate: {endpoint.Destination} {result.StatusCode}", 42 | endpoint.Destination, result.StatusCode); 43 | return; 44 | } 45 | _logger.LogWarning("Certificate: {endpoint.Destination} expiration date: {notAfter}", endpoint.Destination, notAfter); 46 | } 47 | catch 48 | { 49 | _logger.LogError("Error trying get {endpoint.Destination}", endpoint.Destination); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/DbService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class DbService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly PushService _pushService; 7 | 8 | public DbService(ILogger logger, PushService pushService) 9 | { 10 | _logger = logger; 11 | _pushService = pushService; 12 | } 13 | 14 | public async Task CheckDbAsync(Endpoint endpoint) 15 | { 16 | var stopwatch = Stopwatch.StartNew(); 17 | 18 | var dbContext = new ApplicationDbContext(endpoint); 19 | 20 | string status = null; 21 | 22 | try 23 | { 24 | switch (endpoint.Brand) 25 | { 26 | case "MSSQL": 27 | status = dbContext.DbVersion?.FromSqlRaw("Select @@VERSION AS Version").First().Version; 28 | break; 29 | case "MYSQL": 30 | status = dbContext.DbVersion?.FromSqlRaw("Select VERSION() AS Version").First().Version; 31 | break; 32 | case "PGSQL": 33 | status = dbContext.DbVersion?.FromSqlRaw("Select Version()").ToString(); 34 | break; 35 | default: 36 | _logger.LogError("Brand must be MSSQL, MYSQL or PGSQL"); 37 | break; 38 | } 39 | } 40 | catch 41 | { 42 | _logger.LogError("Error trying get {endpoint.Brand}", endpoint.Brand); 43 | } 44 | 45 | if (status is not null) 46 | { 47 | await _pushService.PushAsync(endpoint.PushUri, stopwatch.ElapsedMilliseconds); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/DomainService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class DomainService 4 | { 5 | private readonly ILogger _logger; 6 | private HttpClient _httpClient; 7 | private readonly IHttpClientFactory _httpClientFactory; 8 | private readonly PushService _pushService; 9 | private readonly AppSettings _appSettings; 10 | 11 | public DomainService(ILogger logger, HttpClient httpClient, IHttpClientFactory httpClientFactory, 12 | PushService pushService, AppSettings appSettings) 13 | { 14 | _logger = logger; 15 | _httpClient = httpClient; 16 | _httpClientFactory = httpClientFactory; 17 | _pushService = pushService; 18 | _appSettings = appSettings; 19 | } 20 | 21 | public async Task CheckDomainAsync(Endpoint endpoint) 22 | { 23 | _httpClient = _httpClientFactory.CreateClient(endpoint.IgnoreSSL ? "IgnoreSSL" : "Default"); 24 | 25 | HttpResponseMessage result; 26 | int daysToExpire; 27 | bool closeToExpire; 28 | 29 | try 30 | { 31 | _httpClient.DefaultRequestHeaders.Clear(); 32 | _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"TOKEN={_appSettings.WhoisApiToken}"); 33 | result = await _httpClient.GetAsync($"{_appSettings.WhoisApiUrl.Replace("keep.this", endpoint.Domain)}"); 34 | var content = await result.Content.ReadAsStringAsync(); 35 | var domain = JsonSerializer.Deserialize(content); 36 | 37 | var expiration = DateTime.ParseExact(domain.Expires, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); 38 | 39 | var expires = expiration - DateTime.UtcNow; 40 | daysToExpire = expires.Days; 41 | closeToExpire = daysToExpire < 30; 42 | 43 | _logger.LogInformation("Domain: {endpoint.Destination} expires: {domain.Expires}", endpoint.Domain, domain.Expires); 44 | } 45 | catch 46 | { 47 | _logger.LogError("Error trying get domain expiration for {endpoint.Domain}", endpoint.Domain); 48 | return; 49 | } 50 | 51 | if (!closeToExpire && result is not null && result.IsSuccessStatusCode) 52 | { 53 | await _pushService.PushAsync(endpoint.PushUri, daysToExpire); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/HealthCheckPublisher.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class HealthCheckPublisher : IHealthCheckPublisher 4 | { 5 | private readonly ILogger _logger; 6 | private readonly string _fileName; 7 | private HealthStatus _prevStatus = HealthStatus.Unhealthy; 8 | 9 | public HealthCheckPublisher(ILogger logger) 10 | { 11 | _fileName = "./health"; 12 | _logger = logger; 13 | } 14 | 15 | public Task PublishAsync(HealthReport report, CancellationToken cancellationToken) 16 | { 17 | var fileExists = _prevStatus == HealthStatus.Healthy; 18 | if (report.Status == HealthStatus.Healthy) 19 | { 20 | using var _ = File.Create(_fileName); 21 | } 22 | else if (fileExists) 23 | { 24 | File.Delete(_fileName); 25 | _logger.LogWarning("{status}", report.Status.ToString()); 26 | } 27 | 28 | _prevStatus = report.Status; 29 | return Task.CompletedTask; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/HttpService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class HttpService 4 | { 5 | private readonly ILogger _logger; 6 | private HttpClient _httpClient; 7 | private readonly IHttpClientFactory _httpClientFactory; 8 | private readonly PushService _pushService; 9 | 10 | public HttpService(ILogger logger, HttpClient httpClient, IHttpClientFactory httpClientFactory, PushService pushService) 11 | { 12 | _logger = logger; 13 | _httpClient = httpClient; 14 | _httpClientFactory = httpClientFactory; 15 | _pushService = pushService; 16 | } 17 | 18 | public async Task CheckHttpAsync(Endpoint endpoint) 19 | { 20 | _httpClient = _httpClientFactory.CreateClient(endpoint.IgnoreSSL ? "IgnoreSSL" : "Default"); 21 | 22 | var stopwatch = Stopwatch.StartNew(); 23 | 24 | string content; 25 | 26 | HttpResponseMessage result; 27 | 28 | try 29 | { 30 | result = await _httpClient.GetAsync(endpoint.Destination); 31 | content = await result.Content.ReadAsStringAsync(); 32 | 33 | _logger.LogInformation("Http: {endpoint.Destination} {result.StatusCode}", 34 | endpoint.Destination, result.StatusCode); 35 | 36 | if (endpoint.Keyword != "" && !content.Contains(endpoint.Keyword)) throw new ArgumentNullException(nameof(endpoint), "Keyword not found."); 37 | } 38 | catch 39 | { 40 | _logger.LogError("Error trying get {endpoint.Destination}", endpoint.Destination); 41 | return; 42 | } 43 | 44 | if (result is not null && result.IsSuccessStatusCode) 45 | { 46 | await _pushService.PushAsync(endpoint.PushUri, stopwatch.ElapsedMilliseconds); 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/MonitorsService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class MonitorsService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly AppSettings _appSettings; 7 | 8 | public MonitorsService(ILogger logger, AppSettings appSettings) 9 | { 10 | _logger = logger; 11 | _appSettings = appSettings; 12 | } 13 | 14 | public async Task> GetMonitorsAsync() 15 | { 16 | try 17 | { 18 | using var socket = new SocketIOClient.SocketIO(_appSettings.Url, new SocketIOClient.SocketIOOptions 19 | { 20 | ReconnectionAttempts = 3 21 | }); 22 | 23 | var data = new 24 | { 25 | username = _appSettings.Username, 26 | password = _appSettings.Password, 27 | token = "" 28 | }; 29 | 30 | JsonElement monitorsRaw = new(); 31 | 32 | socket.On("monitorList", response => 33 | { 34 | monitorsRaw = response.GetValue(); 35 | }); 36 | 37 | socket.OnConnected += async (sender, e) => 38 | { 39 | await socket.EmitAsync("login", (ack) => 40 | { 41 | var result = JsonNode.Parse(ack.GetValue(0).ToString()); 42 | if (result["ok"].ToString() != "true") 43 | { 44 | _logger.LogError("Uptime Kuma login failure"); 45 | } 46 | }, data); 47 | }; 48 | 49 | await socket.ConnectAsync(); 50 | 51 | int round = 0; 52 | while (monitorsRaw.ValueKind == JsonValueKind.Undefined) 53 | { 54 | round++; 55 | await Task.Delay(1000); 56 | if (round >= 10) break; 57 | } 58 | 59 | await socket.DisconnectAsync(); 60 | var monitors = JsonSerializer.Deserialize>(monitorsRaw); 61 | return monitors.Values.ToList(); 62 | } 63 | catch 64 | { 65 | _logger.LogError("Error trying to get monitors"); 66 | return null; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/PingService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class PingService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly PushService _pushService; 7 | 8 | public PingService(ILogger logger, PushService pushService) 9 | { 10 | _logger = logger; 11 | _pushService = pushService; 12 | } 13 | 14 | public async Task CheckPingAsync(Endpoint endpoint) 15 | { 16 | Ping ping = new(); 17 | PingReply pingReply = null; 18 | 19 | try 20 | { 21 | pingReply = ping.Send(endpoint.Destination, endpoint.Timeout); 22 | } 23 | catch 24 | { 25 | // Ignore 26 | } 27 | 28 | if (pingReply?.Status == IPStatus.Success) 29 | { 30 | await _pushService.PushAsync(endpoint.PushUri, pingReply.RoundtripTime); 31 | } 32 | _logger.LogInformation("Ping: {pingReply.Address} {pingReply.Status}", pingReply?.Address, pingReply?.Status); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/PushService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class PushService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly HttpClient _httpClient; 7 | private readonly IHttpClientFactory _httpClientFactory; 8 | public PushService(ILogger logger, HttpClient httpClient, IHttpClientFactory httpClientFactory) 9 | { 10 | _logger = logger; 11 | _httpClient = httpClient; 12 | _httpClientFactory = httpClientFactory; 13 | _httpClient = _httpClientFactory.CreateClient(); 14 | } 15 | 16 | public async Task PushAsync(Uri uri, long elapsedMilliseconds) 17 | { 18 | try 19 | { 20 | await _httpClient.GetAsync($"{uri}{elapsedMilliseconds}"); 21 | } 22 | catch 23 | { 24 | _logger.LogError("Error trying to push results to {uri}", uri); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/TcpService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class TcpService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly PushService _pushService; 7 | 8 | public TcpService(ILogger logger, PushService pushService) 9 | { 10 | _logger = logger; 11 | _pushService = pushService; 12 | } 13 | 14 | public async Task CheckTcpAsync(Endpoint endpoint) 15 | { 16 | var stopwatch = Stopwatch.StartNew(); 17 | 18 | TcpClient tcpClient = new(); 19 | 20 | try 21 | { 22 | await tcpClient.ConnectAsync(endpoint.Destination, endpoint.Port); 23 | } 24 | catch 25 | { 26 | // Ignore 27 | } 28 | 29 | if (tcpClient.Connected) 30 | { 31 | await _pushService.PushAsync(endpoint.PushUri, stopwatch.ElapsedMilliseconds); 32 | } 33 | _logger.LogInformation("Tcp: {endpoint.Destination}:{endpoint.Port} Success={tcpClient.Connected}", 34 | endpoint.Destination, endpoint.Port, tcpClient.Connected); 35 | 36 | tcpClient.Dispose(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Services/VersionService.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe.Services; 2 | 3 | public class VersionService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly Configurations _configurations; 7 | 8 | public VersionService(ILogger logger, IConfiguration configuration) 9 | { 10 | _logger = logger; 11 | _configurations = configuration.GetSection(nameof(Configurations)).Get(); 12 | } 13 | 14 | public async Task CheckVersionAsync() 15 | { 16 | var url = _configurations.Url; 17 | if (url == null) 18 | { 19 | _logger.LogError("*** The appsettings.json being used is not compatible with the current version of the application. Please check the repository https://github.com/zimbres/UptimeKumaRemoteProbe for the latest version. ***"); 20 | return await Task.FromResult(true); 21 | } 22 | return await Task.FromResult(false); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/UptimeKumaRemoteProbe.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | disable 6 | enable 7 | dotnet-UptimeKumaRemoteProbe-D033D03F-3E6F-45E9-91FF-0FE1999F7A08 8 | Linux 9 | uptime-kuma.ico 10 | $(PackageVersion) 11 | $(PackageVersion) 12 | 7.0.0.1 13 | Zimbres.Com 14 | https://github.com/zimbres/UptimeKumaRemoteProbe 15 | https://github.com/zimbres/UptimeKumaRemoteProbe 16 | A Remote Probe written in C# to work with Uptime Kuma "Push" monitor type. 17 | Zimbres.Com 18 | zimbres 19 | Uptime Kuma Remote Probe 20 | README.md 21 | true 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | all 40 | runtime; build; native; contentfiles; analyzers; buildtransitive 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/Worker.cs: -------------------------------------------------------------------------------- 1 | namespace UptimeKumaRemoteProbe; 2 | 3 | public class Worker : BackgroundService 4 | { 5 | private readonly ILogger _logger; 6 | private readonly Configurations _configurations; 7 | private readonly PingService _pingService; 8 | private readonly HttpService _httpService; 9 | private readonly TcpService _tcpService; 10 | private readonly CertificateService _certificateService; 11 | private readonly DbService _dbService; 12 | private readonly MonitorsService _monitorsService; 13 | private readonly AppSettings _appSettings; 14 | private readonly DomainService _domainService; 15 | private readonly VersionService _versionService; 16 | private static DateOnly lastDailyExecution; 17 | 18 | public Worker(ILogger logger, IConfiguration configuration, AppSettings appSettings, PingService pingService, HttpService httpService, 19 | TcpService tcpService, CertificateService certificateService, DbService dbService, MonitorsService monitorsService, 20 | DomainService domainService, VersionService versionService) 21 | { 22 | _logger = logger; 23 | _configurations = configuration.GetSection(nameof(Configurations)).Get(); 24 | _appSettings = appSettings; 25 | _pingService = pingService; 26 | _httpService = httpService; 27 | _tcpService = tcpService; 28 | _certificateService = certificateService; 29 | _dbService = dbService; 30 | _monitorsService = monitorsService; 31 | _domainService = domainService; 32 | _versionService = versionService; 33 | } 34 | 35 | protected async override Task ExecuteAsync(CancellationToken stoppingToken) 36 | { 37 | _logger.LogWarning("App version: {version}", Assembly.GetExecutingAssembly().GetName().Version.ToString()); 38 | 39 | if (await _versionService.CheckVersionAsync()) 40 | { 41 | Environment.Exit(0); 42 | } 43 | 44 | if (_appSettings.UpDependency == "") 45 | { 46 | _logger.LogError("Up Dependency is not set."); 47 | Environment.Exit(0); 48 | } 49 | 50 | Ping ping = new(); 51 | PingReply pingReply = null; 52 | 53 | while (!stoppingToken.IsCancellationRequested) 54 | { 55 | if (_appSettings.UpDependency != "") 56 | { 57 | try 58 | { 59 | pingReply = ping.Send(_appSettings.UpDependency, _appSettings.Timeout); 60 | } 61 | catch (Exception ex) 62 | { 63 | _logger.LogError("Network is unreachable. {ex}", ex.Message); 64 | } 65 | } 66 | 67 | if (pingReply?.Status == IPStatus.Success) 68 | { 69 | var monitors = await _monitorsService.GetMonitorsAsync(); 70 | if (monitors is not null) 71 | { 72 | var endpoints = ParseEndpoints(monitors); 73 | await LoopAsync(endpoints); 74 | } 75 | } 76 | else 77 | { 78 | _logger.LogError("Up Dependency is unreachable."); 79 | } 80 | await Task.Delay(_appSettings.Delay, stoppingToken); 81 | } 82 | } 83 | 84 | private List ParseEndpoints(List monitors) 85 | { 86 | var endpoints = new List(); 87 | bool hasProbeMonitor = false; 88 | 89 | foreach (var monitor in monitors) 90 | { 91 | var probe = monitor.Tags.Where(w => w.Name == "Probe").Select(s => s.Value).FirstOrDefault() == _appSettings.ProbeName; 92 | 93 | if (probe) 94 | { 95 | hasProbeMonitor = true; 96 | } 97 | 98 | if (monitor.Active && monitor.Maintenance is false && monitor.Type == "push" && probe) 99 | { 100 | var endpoint = new Endpoint 101 | { 102 | Type = monitor.Tags.Where(w => w.Name == "Type").Select(s => s.Value).First(), 103 | Destination = monitor.Tags.Where(w => w.Name == "Address").Select(s => s.Value).FirstOrDefault() ?? string.Empty, 104 | Timeout = 1000, 105 | PushUri = new Uri($"{_appSettings.Url}api/push/{monitor.PushToken}?status=up&msg=OK&ping="), 106 | Keyword = monitor.Tags.Where(w => w.Name == "Keyword").Select(s => s.Value).FirstOrDefault() ?? string.Empty, 107 | Method = monitor.Tags.Where(w => w.Name == "Method").Select(s => s.Value).FirstOrDefault(), 108 | Brand = monitor.Tags.Where(w => w.Name == "Brand").Select(s => s.Value).FirstOrDefault() ?? string.Empty, 109 | Port = int.Parse(monitor.Tags.Where(w => w.Name == "Port").Select(s => s.Value).FirstOrDefault() ?? "0"), 110 | Domain = monitor.Tags.Where(w => w.Name == "Domain").Select(s => s.Value).FirstOrDefault() ?? string.Empty, 111 | CertificateExpiration = int.Parse(monitor.Tags.Where(w => w.Name == "CertificateExpiration").Select(s => s.Value).FirstOrDefault() ?? "3"), 112 | IgnoreSSL = bool.Parse(monitor.Tags.Where(w => w.Name == "IgnoreSSL").Select(s => s.Value).FirstOrDefault() ?? "False") 113 | }; 114 | endpoints.Add(endpoint); 115 | } 116 | } 117 | 118 | if (!hasProbeMonitor) 119 | { 120 | _logger.LogWarning("No monitors with the specified Probe tag and value {_configurations.ProbeName} were found.", _appSettings.ProbeName); 121 | } 122 | 123 | return endpoints; 124 | } 125 | 126 | private async Task LoopAsync(List endpoints) 127 | { 128 | foreach (var item in endpoints) 129 | { 130 | switch (item.Type) 131 | { 132 | case "Ping": 133 | await _pingService.CheckPingAsync(item); 134 | break; 135 | case "Http": 136 | await _httpService.CheckHttpAsync(item); 137 | break; 138 | case "Tcp": 139 | await _tcpService.CheckTcpAsync(item); 140 | break; 141 | case "Certificate": 142 | await _certificateService.CheckCertificateAsync(item); 143 | break; 144 | case "Database": 145 | item.ConnectionString = $"{_configurations.ConnectionStrings}.{item.Brand}"; 146 | await _dbService.CheckDbAsync(item); 147 | break; 148 | case "Domain": 149 | if (await CheckDailyExecutionAsync()) break; 150 | await _domainService.CheckDomainAsync(item); 151 | break; 152 | default: 153 | break; 154 | } 155 | } 156 | } 157 | 158 | private static async Task CheckDailyExecutionAsync() 159 | { 160 | if (lastDailyExecution == DateOnly.FromDateTime(DateTime.Now)) 161 | { 162 | return await Task.FromResult(true); 163 | } 164 | else 165 | { 166 | lastDailyExecution = DateOnly.FromDateTime(DateTime.Now); 167 | return await Task.FromResult(false); 168 | } 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information", 7 | "System.Net.Http.HttpClient": "Warning", 8 | "Polly": "Warning" 9 | } 10 | }, 11 | "Configurations": { 12 | "Url": "http://192.168.100.190:3001/", 13 | "Username": "admin", 14 | "Password": "Admin123", 15 | "ProbeName": "Home", 16 | "UpDependency": "192.168.1.1", 17 | "Timeout": 1000, 18 | "Delay": 60000, 19 | "ConnectionStrings": { 20 | "PGSQL": "Host=localhost;Database=postgres;Username=postgres;Password=postgres" 21 | }, 22 | "WhoisApiUrl": "https://whoisjson.com/api/v1/whois?domain=keep.this&format=json", 23 | "WhoisApiToken": "whoisjsonApiToken" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/health: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zimbres/UptimeKumaRemoteProbe/fd7597ca640af3814eebfb239381a0bf3a5045d6/src/UptimeKumaRemoteProbe/health -------------------------------------------------------------------------------- /src/UptimeKumaRemoteProbe/uptime-kuma.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zimbres/UptimeKumaRemoteProbe/fd7597ca640af3814eebfb239381a0bf3a5045d6/src/UptimeKumaRemoteProbe/uptime-kuma.ico --------------------------------------------------------------------------------