keepup-admin 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
keepup/factory.py ADDED
@@ -0,0 +1,484 @@
1
+ """Building the application.
2
+
3
+ Everything that used to happen while ``app/main.py`` was being imported happens
4
+ inside ``create_app`` instead: the application is created, its static
5
+ directories mounted, its middleware added and its own endpoints registered.
6
+ That is what makes a second application on this framework possible, and it is
7
+ also what makes the first one testable -- a test can build one with its own
8
+ settings instead of importing a module that builds it as a side effect.
9
+
10
+ The order of the start-up is not free, and two steps in it are the reason this
11
+ file exists rather than a list of calls in each application:
12
+
13
+ * the signing key is demanded before anything else, so a deployment that would
14
+ accept tokens anyone could sign never starts;
15
+ * ``on_startup`` runs before the plugins, because a plugin subscribes to the
16
+ application's bus while initialising and a bus started afterwards would have
17
+ no subscribers.
18
+ """
19
+
20
+ import asyncio
21
+ import json
22
+ import logging
23
+ import os
24
+ from contextlib import asynccontextmanager
25
+
26
+ from fastapi import FastAPI, Request
27
+ from fastapi.middleware.cors import CORSMiddleware
28
+ from fastapi.staticfiles import StaticFiles
29
+ from starlette.middleware.base import BaseHTTPMiddleware
30
+
31
+ from keepup import audit, cluster, logging_setup, notification_bus, web
32
+ from keepup.api_versions import ApiVersionMiddleware
33
+ from keepup.audit import (audit_retention_background, background_buffer_flusher,
34
+ init_incoming_requests_table)
35
+ from keepup.auth import dependencies as auth_dependencies
36
+ from keepup.auth import routes as auth_routes
37
+ from keepup.auth.oidc_routes import register_oidc_routes
38
+ from keepup.events import init_event_manager, register_event_api_routes
39
+ from keepup.instance import get_instance_id
40
+ from keepup.locks import register_lock_routes
41
+ from keepup.logging_setup import init_remote_logging
42
+ from keepup.metrics import register_metrics_routes, update_metrics_background
43
+ from keepup.metrics_retention import metrics_retention_background
44
+ from keepup.modules import register_module_routes
45
+ from keepup.plugins.registry import (
46
+ get_plugins_status,
47
+ initialize_plugins,
48
+ register_plugin_admin_routes,
49
+ run_post_construct_processors,
50
+ )
51
+ from keepup.scheduler import init_scheduler, register_scheduler_routes
52
+ from keepup.settings import KeepupSettings
53
+ from keepup.themes import config_service, register_theme_routes
54
+ from keepup.web import register_web_routes
55
+
56
+ #: What an application may import from this module. Everything else is
57
+ #: internal and may change without notice -- see doc/keepup.md.
58
+ __all__ = [
59
+ "create_app",
60
+ "require_signing_key",
61
+ ]
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+
66
+ def require_signing_key() -> None:
67
+ """Stop the start-up when the token signing key is not configured.
68
+
69
+ Here rather than at import time: importing a module to generate the API
70
+ documentation, or to reach one of its utilities, is not a deployment and
71
+ has no business demanding a production secret. Starting the server is, and
72
+ a server that came up with the placeholder key from the setup examples
73
+ would accept a token anybody could sign for any account.
74
+ """
75
+ from keepup.auth.signing_key import SigningKeyUnavailable, signing_key_problem
76
+
77
+ problem = signing_key_problem()
78
+ if problem:
79
+ logger.critical(problem)
80
+ raise SigningKeyUnavailable(problem)
81
+
82
+
83
+ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
84
+ """The response headers a browser needs in order to refuse things.
85
+
86
+ The panel is an ordinary page, so without X-Frame-Options anybody can frame
87
+ it and read a click as the administrator's. The framework carried none of
88
+ these headers at all, which for a package installed on a public address is
89
+ a default rather than an omission.
90
+ """
91
+
92
+ def __init__(self, app, https=False):
93
+ super().__init__(app)
94
+ self.https = https
95
+
96
+ async def dispatch(self, request, call_next):
97
+ response = await call_next(request)
98
+ response.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
99
+ response.headers.setdefault("X-Content-Type-Options", "nosniff")
100
+ response.headers.setdefault("Referrer-Policy", "same-origin")
101
+ if self.https:
102
+ # Only over TLS: sent over plain HTTP it would be ignored, and a
103
+ # deployment on a local network without TLS must stay reachable.
104
+ response.headers.setdefault(
105
+ "Strict-Transport-Security", "max-age=31536000")
106
+ return response
107
+
108
+
109
+ def apply_settings(settings: KeepupSettings) -> None:
110
+ """Hand each part of the framework the application's values.
111
+
112
+ Done in one place so that what the application supplies is visible as a
113
+ list, rather than as a configure() call hidden in each module's import.
114
+ """
115
+ logging_setup.configure(
116
+ project_name=settings.project_name,
117
+ remote_url=settings.remote_log_url,
118
+ remote_token=settings.remote_log_token,
119
+ flush_interval=settings.remote_log_flush_interval,
120
+ batch_size=settings.remote_log_batch_size,
121
+ )
122
+ audit.configure(redaction=settings.audit_redaction)
123
+ web.configure(
124
+ static_dir=settings.static_dir,
125
+ client_page=settings.client_page,
126
+ version_file=settings.version_file,
127
+ favicon_file=settings.favicon_file,
128
+ )
129
+ auth_dependencies.configure_panel_gate(pending=settings.pending_documents)
130
+ auth_routes.configure(
131
+ password=settings.password_rule,
132
+ login_record=settings.record_login,
133
+ )
134
+ auth_routes.configure_public_config(settings.public_config)
135
+ # Themes are declared here and not when the themes module is imported:
136
+ # there is no application at that point and nothing for it to declare --
137
+ # which is exactly why a declared theme never reached the database. The
138
+ # service brings itself up on this call.
139
+ config_service.register_built_in_themes(settings.built_in_themes)
140
+ config_service.initialize()
141
+
142
+
143
+ class GatedStaticFiles(StaticFiles):
144
+ """Static files the browser rechecks on every load, some of them gated.
145
+
146
+ Starlette sends ETag and Last-Modified but no Cache-Control. Without one a
147
+ browser falls back to heuristic freshness -- roughly a tenth of the file's
148
+ age -- and stops asking the server at all, so an edited module keeps
149
+ serving its old copy until a hard reload. `no-cache` still permits caching;
150
+ it only requires revalidation, which the ETag answers with an empty 304.
151
+
152
+ A gated page is served only while the plugin behind it runs: a page that
153
+ says a payment succeeded, reachable by its address on a deployment with no
154
+ payments, says something untrue.
155
+ """
156
+
157
+ def __init__(self, *args, gated_pages=None, plugin_manager=None, **kwargs):
158
+ super().__init__(*args, **kwargs)
159
+ self.gated_pages = gated_pages or {}
160
+ self.plugin_manager = plugin_manager
161
+
162
+ def file_response(self, *args, **kwargs):
163
+ response = super().file_response(*args, **kwargs)
164
+ response.headers.setdefault("Cache-Control", "no-cache")
165
+ return response
166
+
167
+ async def get_response(self, path, scope):
168
+ plugin_id = self.gated_pages.get(str(path).lstrip("/"))
169
+ if plugin_id and not self._plugin_running(plugin_id):
170
+ from starlette.exceptions import HTTPException as StarletteHTTPException
171
+ raise StarletteHTTPException(status_code=404)
172
+ return await super().get_response(path, scope)
173
+
174
+ def _plugin_running(self, plugin_id: str) -> bool:
175
+ plugin = self.plugin_manager.get_plugin(plugin_id) if self.plugin_manager else None
176
+ return bool(plugin and getattr(plugin, "initialized", False))
177
+
178
+
179
+ def _build_lifespan(settings: KeepupSettings):
180
+ """The start-up and shutdown of one application built from these settings."""
181
+
182
+ manager = settings.plugin_manager
183
+
184
+ @asynccontextmanager
185
+ async def lifespan(app: FastAPI):
186
+ require_signing_key()
187
+
188
+ remote_handler = init_remote_logging()
189
+ metrics_task = asyncio.create_task(update_metrics_background())
190
+ # Snapshots are written every fifteen seconds and without this sweep
191
+ # grow without bound. The sweep runs under a distributed lock: the work
192
+ # is shared across every replica.
193
+ retention_task = asyncio.create_task(metrics_retention_background())
194
+
195
+ init_incoming_requests_table()
196
+ flusher_task = asyncio.create_task(background_buffer_flusher())
197
+ # The audit table had no sweep at all while snapshots and events both
198
+ # had one, so it grew for as long as the deployment ran (keepup-11).
199
+ audit_retention_task = asyncio.create_task(audit_retention_background())
200
+
201
+ event_manager = init_event_manager()
202
+ if event_manager:
203
+ logger.info("Event manager started successfully")
204
+ else:
205
+ logger.warning("Event manager failed to start")
206
+
207
+ register_event_api_routes(app, declared_event_types=settings.declared_event_types)
208
+
209
+ # Before on_startup and the plugins: both subscribe to the bus while
210
+ # initialising, and a bus created after them would have no subscribers.
211
+ bus = await _start_notification_bus(settings.notification_channel)
212
+
213
+ # Before the plugins: a plugin subscribes to the application's bus
214
+ # while initialising, and a bus created after it would have no
215
+ # subscribers.
216
+ if settings.on_startup is not None:
217
+ await settings.on_startup(app)
218
+
219
+ if manager is not None:
220
+ await initialize_plugins(app, manager, config_path=settings.plugins_config_path)
221
+
222
+ scheduler = init_scheduler()
223
+ scheduler.start()
224
+
225
+ logger.info("Scheduler started with tasks:")
226
+ for job in scheduler.get_jobs():
227
+ logger.info(f" - {job.id} (next run: {job.next_run_time})")
228
+
229
+ # After the scheduler: a replica an administrator stopped comes back
230
+ # stopped, and stopping pauses the scheduler.
231
+ controller = cluster.ReplicaController(plugins=_plugin_picture(manager),
232
+ build=_build_label())
233
+ cluster.set_controller(controller)
234
+ controller.launch()
235
+
236
+ if manager is not None:
237
+ asyncio.create_task(run_post_construct_processors(manager))
238
+
239
+ yield
240
+
241
+ await controller.shutdown()
242
+ cluster.set_controller(None)
243
+
244
+ if manager is not None:
245
+ await manager.cleanup_all()
246
+
247
+ if settings.on_shutdown is not None:
248
+ await settings.on_shutdown(app)
249
+
250
+ await _stop_notification_bus(bus)
251
+
252
+ flusher_task.cancel()
253
+ metrics_task.cancel()
254
+ retention_task.cancel()
255
+ audit_retention_task.cancel()
256
+ for task in (flusher_task, metrics_task, retention_task, audit_retention_task):
257
+ try:
258
+ await task
259
+ except asyncio.CancelledError:
260
+ # Each task is awaited on its own: in a shared try the first
261
+ # cancellation left the block and the rest stayed uncancelled.
262
+ pass
263
+
264
+ await flush_remaining_logs()
265
+
266
+ if scheduler:
267
+ scheduler.shutdown()
268
+ logger.info("Scheduler stopped")
269
+
270
+ if remote_handler:
271
+ remote_handler.wrapper.force_flush()
272
+
273
+ return lifespan
274
+
275
+
276
+ async def _start_notification_bus(channel):
277
+ """Install and start the replicas' bus on the application's channel, if it named one."""
278
+ if not channel:
279
+ return None
280
+ bus = notification_bus.NotificationBus(get_instance_id(), channel)
281
+ notification_bus.set_notification_bus(bus)
282
+ await bus.start()
283
+ return bus
284
+
285
+
286
+ async def _stop_notification_bus(bus):
287
+ if bus is None:
288
+ return
289
+ await bus.stop()
290
+ if notification_bus.get_notification_bus() is bus:
291
+ notification_bus.set_notification_bus(None)
292
+
293
+
294
+ def _plugin_picture(manager):
295
+ """What runs in this replica and what awaits its restart, for the cluster registry.
296
+
297
+ The same report /api/admin/plugins answers with, so the two cannot disagree.
298
+ """
299
+ async def picture():
300
+ if manager is None:
301
+ return cluster.PluginPicture([], [])
302
+ try:
303
+ rows = (await get_plugins_status(manager)).get("plugins", [])
304
+ except Exception as error:
305
+ # The replica still has to publish itself; an unreadable plugin
306
+ # report must not make it look gone.
307
+ logger.warning(f"Cluster: plugin report unavailable: {error}")
308
+ rows = []
309
+ return cluster.PluginPicture(
310
+ running=[row["id"] for row in rows if row.get("initialized")],
311
+ pending=[row["id"] for row in rows if row.get("pending_restart")])
312
+ return picture
313
+
314
+
315
+ def _build_label():
316
+ """The build this replica runs, from the version file build_image.sh writes."""
317
+ try:
318
+ with open(os.path.join(web.STATIC_DIR, web.VERSION_FILE), encoding="utf-8") as f:
319
+ version = json.load(f)
320
+ except (OSError, ValueError):
321
+ return None
322
+ label = str(version.get("version") or "")
323
+ if version.get("build_number"):
324
+ label += f" #{version['build_number']}"
325
+ return label or None
326
+
327
+
328
+ async def flush_remaining_logs():
329
+ """Ship the remaining incoming-request logs at shutdown."""
330
+ try:
331
+ logger.info("Flushing remaining incoming request logs...")
332
+ count = await audit.IncomingRequestLogger.flush_buffer()
333
+ logger.info(f"Flushed {count} remaining logs")
334
+ except Exception as e:
335
+ logger.error(f"Error flushing remaining logs: {str(e)}")
336
+
337
+
338
+ def _create_stripped_app(settings: KeepupSettings) -> FastAPI:
339
+ """The application DISABLE_HTTP_SERVER asks for: metrics and a raw log.
340
+
341
+ Not a smaller version of the real one -- a different one. Routes are absent
342
+ rather than disabled, which is why a request that 404s here is expected and
343
+ not a fault to look for elsewhere.
344
+ """
345
+ from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
346
+ from fastapi.responses import Response as FastAPIResponse
347
+
348
+ app = FastAPI(title=settings.title)
349
+
350
+ @app.middleware("http")
351
+ async def log_raw_request(request: Request, call_next):
352
+ """Middleware logging raw HTTP requests."""
353
+ logger.info("=" * 80)
354
+ logger.info("📥 RAW REQUEST RECEIVED")
355
+ logger.info(f"Method: {request.method}")
356
+ logger.info(f"URL: {request.url}")
357
+ logger.info(f"Path: {request.url.path}")
358
+ logger.info(f"Query params: {dict(request.query_params)}")
359
+
360
+ # Header names only, and never their values. This used to write every
361
+ # header out in full -- Authorization and Cookie among them -- and then
362
+ # the same thing again as text and as hex, and RemoteLoggerWrapper
363
+ # shipped the lot to a collector. One environment variable turned a
364
+ # replica into a device that records other people's credentials
365
+ # (task keepup-13).
366
+ logger.info(f"Header names: {', '.join(request.headers.keys())}")
367
+
368
+ body = await request.body()
369
+ if body:
370
+ try:
371
+ logger.info(f"Body: {len(body)} bytes")
372
+ except Exception:
373
+ logger.info(f"Body (binary): {body.hex()[:1000]}")
374
+
375
+ logger.info("=" * 80)
376
+
377
+ response = await call_next(request)
378
+ logger.info(f"📤 RESPONSE: {response.status_code}")
379
+ return response
380
+
381
+ @app.get("/metrics")
382
+ async def metrics():
383
+ return FastAPIResponse(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)
384
+
385
+ return app
386
+
387
+
388
+ def create_app(settings: KeepupSettings = None) -> FastAPI:
389
+ """Build an application from these settings.
390
+
391
+ The plugin manager, when the settings carry one, is left on
392
+ ``app.state.plugin_manager``: the entry point re-exports it, because that
393
+ is the object plugins reach for.
394
+ """
395
+ settings = settings or KeepupSettings()
396
+ apply_settings(settings)
397
+
398
+ if settings.disable_http_server:
399
+ return _create_stripped_app(settings)
400
+
401
+ # /docs belongs to the public gateway reference, so the interactive API docs
402
+ # live under /api. FastAPI registers them in the constructor, ahead of any
403
+ # app route, so a page at /docs could not shadow them otherwise.
404
+ app = FastAPI(
405
+ title=settings.title,
406
+ lifespan=_build_lifespan(settings),
407
+ docs_url=settings.docs_url,
408
+ redoc_url=settings.redoc_url,
409
+ )
410
+ app.state.settings = settings
411
+ app.state.plugin_manager = settings.plugin_manager
412
+
413
+ for mount in settings.static_mounts:
414
+ app.mount(
415
+ mount.path,
416
+ GatedStaticFiles(
417
+ directory=mount.directory,
418
+ gated_pages=settings.gated_pages,
419
+ plugin_manager=settings.plugin_manager,
420
+ ),
421
+ name=mount.name,
422
+ )
423
+
424
+ # The package's own shell, always mounted and never from the working
425
+ # directory: an installed keepup renders its panel out of its own files,
426
+ # and an application that ships none still gets one (keepup-3).
427
+ app.mount(
428
+ settings.shell_mount,
429
+ GatedStaticFiles(
430
+ directory=web.SHELL_DIR,
431
+ gated_pages={},
432
+ plugin_manager=None,
433
+ ),
434
+ name="keepup-shell",
435
+ )
436
+
437
+ # Empty unless the application named origins: see KeepupSettings.
438
+ app.add_middleware(
439
+ CORSMiddleware,
440
+ allow_origins=list(settings.cors_origins),
441
+ # The panel session is a cookie now. With credentials allowed, Starlette
442
+ # answers a request carrying cookies with that request's own origin, and
443
+ # any site could read the panel's answers in the user's name.
444
+ allow_credentials=False,
445
+ allow_methods=["*"],
446
+ allow_headers=["*"],
447
+ )
448
+
449
+ if settings.security_headers:
450
+ app.add_middleware(SecurityHeadersMiddleware,
451
+ https=os.getenv("SSL_ENABLED", "false").lower() == "true")
452
+
453
+ # A replica an administrator stopped refuses the API (keepup/cluster.py).
454
+ # Added before the version middleware, so it runs inside it and sees the
455
+ # registered path.
456
+ app.add_middleware(cluster.StoppedReplicaGate)
457
+
458
+ # Versioned paths (/api/v1, /ws/v1) reach the same handlers; added last, so it
459
+ # runs first and every middleware and route below sees the registered path.
460
+ app.add_middleware(ApiVersionMiddleware)
461
+
462
+ if os.getenv('SSL_ENABLED', 'false').lower() == 'true' \
463
+ and os.getenv('FORCE_HTTPS', 'false').lower() == 'true':
464
+ from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
465
+
466
+ app.add_middleware(HTTPSRedirectMiddleware)
467
+ logger.info("HTTPS redirect middleware enabled - HTTP requests will be redirected to HTTPS")
468
+
469
+ register_web_routes(app)
470
+ register_module_routes(app)
471
+ # Registered only when the application configured a provider; without one
472
+ # the paths do not exist at all.
473
+ register_oidc_routes(app, settings)
474
+ register_metrics_routes(app, public=settings.metrics_public)
475
+ register_lock_routes(app)
476
+ register_scheduler_routes(app)
477
+ cluster.register_cluster_routes(app)
478
+ register_theme_routes(app, config_service)
479
+ if settings.plugin_manager is not None:
480
+ register_auth_routes = auth_routes.register_auth_routes
481
+ register_auth_routes(app, settings.plugin_manager)
482
+ register_plugin_admin_routes(app, settings.plugin_manager)
483
+
484
+ return app
keepup/instance.py ADDED
@@ -0,0 +1,46 @@
1
+ """Identity of a single running replica.
2
+
3
+ The application runs as several replicas against one database, so almost
4
+ everything written down -- a lock, a metric, an event -- has to say which
5
+ replica wrote it.
6
+ """
7
+
8
+ import os
9
+ import socket
10
+
11
+ #: What an application may import from this module. Everything else is
12
+ #: internal and may change without notice -- see doc/keepup.md.
13
+ __all__ = [
14
+ "get_instance_id",
15
+ "get_instance_name",
16
+ ]
17
+
18
+ DEFAULT_INSTANCE_NAME = "default-instance"
19
+
20
+
21
+ def get_instance_id() -> str:
22
+ """Return a unique identifier for this instance."""
23
+ return f"{socket.gethostname()}-{os.getpid()}"
24
+
25
+
26
+ def get_instance_name() -> str:
27
+ """Return the instance name used in logs and events.
28
+
29
+ Precedence:
30
+ 1. INSTANCE_NAME environment variable
31
+ 2. HOSTNAME environment variable
32
+ 3. The system host name
33
+ 4. "default-instance"
34
+ """
35
+ instance_name = os.environ.get('INSTANCE_NAME')
36
+ if instance_name:
37
+ return instance_name
38
+
39
+ hostname = os.environ.get('HOSTNAME')
40
+ if hostname:
41
+ return hostname
42
+
43
+ try:
44
+ return socket.gethostname()
45
+ except Exception:
46
+ return DEFAULT_INSTANCE_NAME