Skip to content

Commit

Permalink
Merge pull request #160 from smk4664/slack_socket_mode
Browse files Browse the repository at this point in the history
Slack socket mode
  • Loading branch information
smk4664 authored Oct 28, 2022
2 parents 8ea9c93 + bb7816c commit 897a0e9
Show file tree
Hide file tree
Showing 22 changed files with 778 additions and 431 deletions.
10 changes: 0 additions & 10 deletions creds.env.example

This file was deleted.

4 changes: 2 additions & 2 deletions development/docker-compose.requirements.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ services:
image: "redis:6-alpine"
command:
- "sh"
- "-c" # this is to evaluate the $REDIS_PASSWORD from the env
- "redis-server --appendonly yes --requirepass $$REDIS_PASSWORD"
- "-c" # this is to evaluate the $NAUTOBOT_REDIS_PASSWORD from the env
- "redis-server --appendonly yes --requirepass $$NAUTOBOT_REDIS_PASSWORD"
env_file:
- "dev.env"
- "creds.env"
Expand Down
17 changes: 17 additions & 0 deletions development/docker-compose.socket.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
version: "3.4"
services:
socket:
image: "nautobot-chatops-plugin/nautobot:${NAUTOBOT_VER}-py${PYTHON_VER}"
env_file:
- "dev.env"
- "creds.env"
tty: true
entrypoint: "nautobot-server start_slack_socket"
depends_on:
- "nautobot"
healthcheck:
disable: true
volumes:
- "./nautobot_config.py:/opt/nautobot/nautobot_config.py"
- "../:/source"
297 changes: 83 additions & 214 deletions development/nautobot_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,78 +2,97 @@
import os
import sys

from distutils.util import strtobool

from django.core.exceptions import ImproperlyConfigured
from nautobot.core.settings import * # noqa: F401,F403 pylint: disable=wildcard-import,unused-wildcard-import

# pylint: disable=line-too-long


def is_truthy(arg):
"""Convert "truthy" strings into Booleans.
Examples:
>>> is_truthy('yes')
True
Args:
arg (str): Truthy string (True values are y, yes, t, true, on and 1; false values are n, no,
f, false, off and 0. Raises ValueError if val is anything else.
"""
if isinstance(arg, bool):
return arg
return bool(strtobool(arg))
from nautobot.core.settings_funcs import parse_redis_connection


# Enforce required configuration parameters
for key in [
"NAUTOBOT_ALLOWED_HOSTS",
"NAUTOBOT_DB_USER",
"NAUTOBOT_DB_PASSWORD",
"NAUTOBOT_REDIS_HOST",
"NAUTOBOT_REDIS_PASSWORD",
"NAUTOBOT_SECRET_KEY",
]:
if not os.environ.get(key):
raise ImproperlyConfigured(f"Required environment variable {key} is missing.")

# For reference see https://nautobot.readthedocs.io/en/latest/configuration/required-settings/
# Based on config from nautobot-server init

#########################
# #
# Required settings #
# #
#########################

# This is a list of valid fully-qualified domain names (FQDNs) for the Nautobot server. Nautobot will not permit write
# access to the server via any other hostnames. The first FQDN in the list will be treated as the preferred name.
#
# Example: ALLOWED_HOSTS = ['nautobot.example.com', 'nautobot.internal.local']
ALLOWED_HOSTS = os.getenv("NAUTOBOT_ALLOWED_HOSTS", "").split(" ")
SECRET_KEY = os.getenv("NAUTOBOT_SECRET_KEY", "")

nautobot_db_engine = os.getenv("NAUTOBOT_DB_ENGINE", "django.db.backends.postgresql")
default_db_settings = {
"django.db.backends.postgresql": {
"NAUTOBOT_DB_PORT": "5432",
},
"django.db.backends.mysql": {
"NAUTOBOT_DB_PORT": "3306",
},
}
DATABASES = {
"default": {
"NAME": os.getenv("NAUTOBOT_DB_NAME", "nautobot"), # Database name
"USER": os.getenv("NAUTOBOT_DB_USER", ""), # Database username
"PASSWORD": os.getenv("NAUTOBOT_DB_PASSWORD", ""), # Datbase password
"PASSWORD": os.getenv("NAUTOBOT_DB_PASSWORD", ""), # Database password
"HOST": os.getenv("NAUTOBOT_DB_HOST", "localhost"), # Database server
"PORT": os.getenv("NAUTOBOT_DB_PORT", ""), # Database port (leave blank for default)
"CONN_MAX_AGE": int(os.environ.get("NAUTOBOT_DB_TIMEOUT", 300)), # Database timeout
"ENGINE": os.getenv("NAUTOBOT_DB_ENGINE", "django.db.backends.postgresql"), # Database driver
"PORT": os.getenv(
"NAUTOBOT_DB_PORT", default_db_settings[nautobot_db_engine]["NAUTOBOT_DB_PORT"]
), # Database port, default to postgres
"CONN_MAX_AGE": int(os.getenv("NAUTOBOT_DB_TIMEOUT", 300)), # Database timeout
"ENGINE": nautobot_db_engine,
}
}

# Redis variables
REDIS_HOST = os.getenv("NAUTOBOT_REDIS_HOST", "localhost")
REDIS_PORT = os.getenv("NAUTOBOT_REDIS_PORT", "6379")
REDIS_PASSWORD = os.getenv("NAUTOBOT_REDIS_PASSWORD", "")
#
# Debug
#

DEBUG = True

# Django Debug Toolbar
DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": lambda _request: DEBUG and not TESTING}

if DEBUG and "debug_toolbar" not in INSTALLED_APPS: # noqa: F405
INSTALLED_APPS.append("debug_toolbar") # noqa: F405
if DEBUG and "debug_toolbar.middleware.DebugToolbarMiddleware" not in MIDDLEWARE: # noqa: F405
MIDDLEWARE.insert(0, "debug_toolbar.middleware.DebugToolbarMiddleware") # noqa: F405

#
# Logging
#

LOG_LEVEL = "DEBUG" if DEBUG else "INFO"

TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"

# Verbose logging during normal development operation, but quiet logging during unit test execution
if not TESTING:
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"normal": {
"format": "%(asctime)s.%(msecs)03d %(levelname)-7s %(name)s :\n %(message)s",
"datefmt": "%H:%M:%S",
},
"verbose": {
"format": "%(asctime)s.%(msecs)03d %(levelname)-7s %(name)-20s %(filename)-15s %(funcName)30s() :\n %(message)s",
"datefmt": "%H:%M:%S",
},
},
"handlers": {
"normal_console": {
"level": "INFO",
"class": "logging.StreamHandler",
"formatter": "normal",
},
"verbose_console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "verbose",
},
},
"loggers": {
"django": {"handlers": ["normal_console"], "level": "INFO"},
"nautobot": {
"handlers": ["verbose_console" if DEBUG else "normal_console"],
"level": LOG_LEVEL,
},
},
}

# Check for Redis SSL
REDIS_SCHEME = "redis"
REDIS_SSL = is_truthy(os.getenv("REDIS_SSL", "False"))
if REDIS_SSL:
REDIS_SCHEME = "rediss"
#
# Redis
#

# The django-redis cache is used to establish concurrent locks using Redis. The
# django-rq settings will use the same instance/database by default.
Expand All @@ -83,127 +102,19 @@ def is_truthy(arg):
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": f"{REDIS_SCHEME}://{REDIS_HOST}:{REDIS_PORT}/0",
"LOCATION": parse_redis_connection(redis_database=0),
"TIMEOUT": 300,
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": REDIS_PASSWORD,
},
}
}

# REDIS CACHEOPS
CACHEOPS_REDIS = f"{REDIS_SCHEME}://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/1"

# This key is used for secure generation of random numbers and strings. It must never be exposed outside of this file.
# For optimal security, SECRET_KEY should be at least 50 characters in length and contain a mix of letters, numbers, and
# symbols. Nautobot will not run without this defined. For more information, see
# https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-SECRET_KEY
SECRET_KEY = os.environ["NAUTOBOT_SECRET_KEY"]


#########################
# #
# Optional settings #
# #
#########################

# Specify one or more name and email address tuples representing Nautobot administrators. These people will be notified of
# application errors (assuming correct email settings are provided).
ADMINS = [
# ['John Doe', '[email protected]'],
]
# RQ_QUEUES is not set here because it just uses the default that gets imported
# up top via `from nautobot.core.settings import *`.

# Optionally display a persistent banner at the top and/or bottom of every page. HTML is allowed. To display the same
# content in both banners, define BANNER_TOP and set BANNER_BOTTOM = BANNER_TOP.
BANNER_TOP = os.environ.get("BANNER_TOP", "")
BANNER_BOTTOM = os.environ.get("BANNER_BOTTOM", "")

# Text to include on the login page above the login form. HTML is allowed.
BANNER_LOGIN = os.environ.get("BANNER_LOGIN", "")

# Base URL path if accessing Nautobot within a directory. For example, if installed at https://example.com/nautobot/, set:
# BASE_PATH = 'nautobot/'
BASE_PATH = os.environ.get("BASE_PATH", "")

# Cache timeout in seconds. Set to 0 to dissable caching. Defaults to 900 (15 minutes)
CACHEOPS_DEFAULTS = {"timeout": 900}

# The file path where jobs will be stored. A trailing slash is not needed. Note that the default value of
# this setting is inside the invoking user's home directory.
# JOBS_ROOT = os.path.expanduser('~/.nautobot/jobs')

# Set to True to enable server debugging. WARNING: Debugging introduces a substantial performance penalty and may reveal
# sensitive information about your installation. Only enable debugging while performing testing. Never enable debugging
# on a production system.
DEBUG = is_truthy(os.environ.get("DEBUG", False))

# Enforcement of unique IP space can be toggled on a per-VRF basis. To enforce unique IP space
# within the global table (all prefixes and IP addresses not assigned to a VRF), set
# ENFORCE_GLOBAL_UNIQUE to True.
ENFORCE_GLOBAL_UNIQUE = is_truthy(os.environ.get("ENFORCE_GLOBAL_UNIQUE", False))

# Exempt certain models from the enforcement of view permissions. Models listed here will be viewable by all users and
# by anonymous users. List models in the form `<app>.<model>`. Add '*' to this list to exempt all models.
EXEMPT_VIEW_PERMISSIONS = [
# 'dcim.site',
# 'dcim.region',
# 'ipam.prefix',
]

# A list of strings designating all applications that are enabled in this Django installation. Each string should be a dotted Python path to an application configuration class (preferred), or a package containing an application.
# http://nautobot.readthedocs.io/configuration/optional-settings/#extra-applications
EXTRA_INSTALLED_APPS = []

# HTTP proxies Nautobot should use when sending outbound HTTP requests (e.g. for webhooks).
# HTTP_PROXIES = {
# 'http': 'http://10.10.1.10:3128',
# 'https': 'http://10.10.1.10:1080',
# }

# IP addresses recognized as internal to the system. The debugging toolbar will be available only to clients accessing
# Nautobot from an internal IP.
INTERNAL_IPS = ("127.0.0.1", "::1")

# The file path where jobs will be stored. A trailing slash is not needed. Note that the default value of
# this setting is derived from the installed location.
JOBS_ROOT = os.environ.get("JOBS_ROOT", os.path.expanduser("~/.nautobot/jobs"))

LOG_LEVEL = os.environ.get("LOG_LEVEL", "DEBUG" if DEBUG else "INFO")

# Enable custom logging. Please see the Django documentation for detailed guidance on configuring custom logs:
# https://docs.djangoproject.com/en/stable/topics/logging/
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "{asctime} {levelname} {message} - {name} - {module} - {pathname}:{lineno}",
"datefmt": "%H:%M:%S",
"style": "{",
},
},
"handlers": {"console": {"level": "DEBUG", "class": "rq.utils.ColorizingStreamHandler", "formatter": "verbose"}},
"root": {"handlers": ["console"], "level": LOG_LEVEL},
}

# Setting this to True will display a "maintenance mode" banner at the top of every page.
MAINTENANCE_MODE = is_truthy(os.environ.get("MAINTENANCE_MODE", False))

# An API consumer can request an arbitrary number of objects =by appending the "limit" parameter to the URL (e.g.
# "?limit=1000"). This setting defines the maximum limit. Setting it to 0 or None will allow an API consumer to request
# all objects by specifying "?limit=0".
MAX_PAGE_SIZE = int(os.environ.get("MAX_PAGE_SIZE", 1000))

# The file path where uploaded media such as image attachments are stored. A trailing slash is not needed. Note that
# the default value of this setting is within the invoking user's home directory
MEDIA_ROOT = os.environ.get("MEDIA_ROOT", os.path.expanduser("~/.nautobot/media"))

# Expose Prometheus monitoring metrics at the HTTP endpoint '/metrics'
METRICS_ENABLED = True

# Determine how many objects to display per page within a list. (Default: 50)
PAGINATE_COUNT = int(os.environ.get("PAGINATE_COUNT", 50))
# Redis Cacheops
CACHEOPS_REDIS = parse_redis_connection(redis_database=1)

# Enable installed plugins. Add the name of each plugin to the list.
PLUGINS = ["nautobot_chatops", "nautobot_capacity_metrics"]
Expand All @@ -217,6 +128,7 @@ def is_truthy(arg):
"enable_webex": True,
"microsoft_app_id": os.environ.get("MICROSOFT_APP_ID"),
"microsoft_app_password": os.environ.get("MICROSOFT_APP_PASSWORD"),
"slack_app_token": os.environ.get("SLACK_APP_TOKEN"),
"slack_api_token": os.environ.get("SLACK_API_TOKEN"),
"slack_signing_secret": os.environ.get("SLACK_SIGNING_SECRET"),
"slack_slash_command_prefix": os.environ.get("SLACK_SLASH_COMMAND_PREFIX", "/"),
Expand All @@ -227,46 +139,3 @@ def is_truthy(arg):
"mattermost_url": os.environ.get("MATTERMOST_URL"),
},
}


# When determining the primary IP address for a device, IPv6 is preferred over IPv4 by default. Set this to True to
# prefer IPv4 instead.
PREFER_IPV4 = is_truthy(os.environ.get("PREFER_IPV4", False))

# Remote authentication support
REMOTE_AUTH_ENABLED = False
REMOTE_AUTH_BACKEND = "nautobot.core.authentication.RemoteUserBackend"
REMOTE_AUTH_HEADER = "HTTP_REMOTE_USER"
REMOTE_AUTH_AUTO_CREATE_USER = True
REMOTE_AUTH_DEFAULT_GROUPS = []
REMOTE_AUTH_DEFAULT_PERMISSIONS = {}

# This determines how often the GitHub API is called to check the latest release of Nautobot. Must be at least 1 hour.
RELEASE_CHECK_TIMEOUT = 24 * 3600

# Maximum execution time for background tasks, in seconds.
RQ_DEFAULT_TIMEOUT = 300

# Configure SSO, for more information see docs/configuration/authentication/sso.md
SOCIAL_AUTH_ENABLED = False

# By default uploaded media is stored on the local filesystem. Using Django-storages is also supported. Provide the
# class path of the storage driver in STORAGE_BACKEND and any configuration options in STORAGE_CONFIG. For example:
# STORAGE_BACKEND = 'storages.backends.s3boto3.S3Boto3Storage'
# STORAGE_CONFIG = {
# 'AWS_ACCESS_KEY_ID': 'Key ID',
# 'AWS_SECRET_ACCESS_KEY': 'Secret',
# 'AWS_STORAGE_BUCKET_NAME': 'nautobot',
# 'AWS_S3_REGION_NAME': 'eu-west-1',
# }

# Time zone (default: UTC)
TIME_ZONE = os.environ.get("TIME_ZONE", "UTC")

# Django Debug Toolbar
TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": lambda _request: DEBUG and not TESTING}
#
# Celery settings are not defined here because they can be overloaded with
# environment variables. By default they use `CACHES["default"]["LOCATION"]`.
#
1 change: 1 addition & 0 deletions docs/admin/compatibility_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ While that last supported version will not be strictly enforced via the `max_ver
| 1.7.X | 1.0.0 | 1.2.99 [Official] |
| 1.8.X | 1.1.0 | 1.4.99 [Official] |
| 1.9.X | 1.2.0 | 1.5.99 [Official] |
| 1.10.X | 1.3.0 | 1.5.99 [Official] |
Loading

0 comments on commit 897a0e9

Please sign in to comment.