From 523bdfe8964497556ee1c4841827eb8abf40855a Mon Sep 17 00:00:00 2001 From: sysang Date: Mon, 29 Aug 2022 01:09:30 +0700 Subject: [PATCH] Complete integration of chatwoot --- .cw.env | 208 ++++++++++++++++++ .cw.env.template | 208 ++++++++++++++++++ .gitignore | 2 + .../chatroom/templates/chatroom/index.html | 18 +- botserver-app/addons/channels/chatwoot.py | 30 ++- .../addons/channels/cwwebsite_output.py | 3 +- ...edentials.yml => credentials.template.yml} | 0 deployment_note.md | 11 + docker-compose.yml | 85 +++++-- docker/entrypoints/rails.sh | 34 +++ 10 files changed, 555 insertions(+), 44 deletions(-) create mode 100644 .cw.env create mode 100644 .cw.env.template rename botserver-app/{credentials.yml => credentials.template.yml} (100%) create mode 100644 docker/entrypoints/rails.sh diff --git a/.cw.env b/.cw.env new file mode 100644 index 0000000..e01a01a --- /dev/null +++ b/.cw.env @@ -0,0 +1,208 @@ +# Used to verify the integrity of signed cookies. so ensure a secure value is set +SECRET_KEY_BASE='4ZyW8MpYUkw2hWf4ZzW8MpYUkw2hWf4ZzW8MpYUkw2hWf' + +# Replace with the URL you are planning to use for your app +FRONTEND_URL='http://cs.rasachatbot.sysang' + +# If the variable is set, all non-authenticated pages would fallback to the default locale. +# Whenever a new account is created, the default language will be DEFAULT_LOCALE instead of en +# DEFAULT_LOCALE=en + +# If you plan to use CDN for your assets, set Asset CDN Host +ASSET_CDN_HOST= + +# Force all access to the app over SSL, default is set to false +FORCE_SSL=false + +# This lets you control new sign ups on your chatwoot installation +# true : default option, allows sign ups +# false : disables all the end points related to sign ups +# api_only: disables the UI for signup, but you can create sign ups via the account apis +ENABLE_ACCOUNT_SIGNUP=false + +# Redis config +REDIS_URL=redis://redis:6379 +# If you are using docker-compose, set this variable's value to be any string, +# which will be the password for the redis service running inside the docker-compose +# to make it secure +REDIS_PASSWORD='qwer1234' +# Redis Sentinel can be used by passing list of sentinel host and ports e,g. sentinel_host1:port1,sentinel_host2:port2 +REDIS_SENTINELS= +# Redis sentinel master name is required when using sentinel, default value is "mymaster". +# You can find list of master using "SENTINEL masters" command +REDIS_SENTINEL_MASTER_NAME= + +# Redis premium breakage in heroku fix +# enable the following configuration +# ref: https://github.com/chatwoot/chatwoot/issues/2420 +# REDIS_OPENSSL_VERIFY_MODE=none + +# Postgres Database config variables +# You can leave POSTGRES_DATABASE blank. The default name of +# the database in the production environment is chatwoot_production +POSTGRES_HOST='cwdb' +POSTGRES_USERNAME='postgres' +POSTGRES_PASSWORD='qwer1234' +POSTGRES_DATABASE='chatwoot' +RAILS_ENV='production' +RAILS_MAX_THREADS=5 + +# The email from which all outgoing emails are sent +# could user either `email@yourdomain.com` or `BrandName ` +MAILER_SENDER_EMAIL="Sy Sang " + +#SMTP domain key is set up for HELO checking +SMTP_DOMAIN=chatwoot.com +# the default value is set "mailhog" and is used by docker-compose for development environments, +# Set the value as "localhost" or your SMTP address in other environments +SMTP_ADDRESS=mailhog +SMTP_PORT=1025 +SMTP_USERNAME= +SMTP_PASSWORD= +# plain,login,cram_md5 +SMTP_AUTHENTICATION= +SMTP_ENABLE_STARTTLS_AUTO=true +# Can be: 'none', 'peer', 'client_once', 'fail_if_no_peer_cert', see http://api.rubyonrails.org/classes/ActionMailer/Base.html +SMTP_OPENSSL_VERIFY_MODE=peer +# Comment out the following environment variables if required by your SMTP server +# SMTP_TLS= +# SMTP_SSL= + +# Mail Incoming +# This is the domain set for the reply emails when conversation continuity is enabled +MAILER_INBOUND_EMAIL_DOMAIN= +# Set this to appropriate ingress channel with regards to incoming emails +# Possible values are : +# relay for Exim, Postfix, Qmail +# mailgun for Mailgun +# mandrill for Mandrill +# postmark for Postmark +# sendgrid for Sendgrid +RAILS_INBOUND_EMAIL_SERVICE= +# Use one of the following based on the email ingress service +# Ref: https://edgeguides.rubyonrails.org/action_mailbox_basics.html +RAILS_INBOUND_EMAIL_PASSWORD= +MAILGUN_INGRESS_SIGNING_KEY= +MANDRILL_INGRESS_API_KEY= + +# Storage +ACTIVE_STORAGE_SERVICE=local + +# Amazon S3 +# documentation: https://www.chatwoot.com/docs/configuring-s3-bucket-as-cloud-storage +S3_BUCKET_NAME= +AWS_ACCESS_KEY_ID= +AWS_SECRET_ACCESS_KEY= +AWS_REGION= + +# Log settings +# Disable if you want to write logs to a file +RAILS_LOG_TO_STDOUT=true +LOG_LEVEL=info +LOG_SIZE=500 + +### This environment variables are only required if you are setting up social media channels + +# Facebook +# documentation: https://www.chatwoot.com/docs/facebook-setup +FB_VERIFY_TOKEN= +FB_APP_SECRET= +FB_APP_ID= + +# https://developers.facebook.com/docs/messenger-platform/instagram/get-started#app-dashboard +IG_VERIFY_TOKEN= + +# Twitter +# documentation: https://www.chatwoot.com/docs/twitter-app-setup +TWITTER_APP_ID= +TWITTER_CONSUMER_KEY= +TWITTER_CONSUMER_SECRET= +TWITTER_ENVIRONMENT= + +#slack integration +SLACK_CLIENT_ID= +SLACK_CLIENT_SECRET= + +### Change this env variable only if you are using a custom build mobile app +## Mobile app env variables +IOS_APP_ID=L7YLMN4634.com.chatwoot.app +ANDROID_BUNDLE_ID=com.chatwoot.app + +# https://developers.google.com/android/guides/client-auth (use keytool to print the fingerprint in the first section) +ANDROID_SHA256_CERT_FINGERPRINT=AC:73:8E:DE:EB:56:EA:CC:10:87:02:A7:65:37:7B:38:D4:5D:D4:53:F8:3B:FB:D3:C6:28:64:1D:AA:08:1E:D8 + +### Smart App Banner +# https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/PromotingAppswithAppBanners/PromotingAppswithAppBanners.html +# You can find your app-id in https://itunesconnect.apple.com +#IOS_APP_IDENTIFIER=1495796682 + +## Push Notification +## generate a new key value here : https://d3v.one/vapid-key-generator/ +# VAPID_PUBLIC_KEY= +# VAPID_PRIVATE_KEY= +# +# for mobile apps +# FCM_SERVER_KEY= + +## Bot Customizations +USE_INBOX_AVATAR_FOR_BOT=true + +### APM and Error Monitoring configurations +## Elastic APM +## https://www.elastic.co/guide/en/apm/agent/ruby/current/getting-started-rails.html +# ELASTIC_APM_SERVER_URL= +# ELASTIC_APM_SECRET_TOKEN= + +## Sentry +# SENTRY_DSN= + +## Scout +## https://scoutapm.com/docs/ruby/configuration +# SCOUT_KEY=YOURKEY +# SCOUT_NAME=YOURAPPNAME (Production) +# SCOUT_MONITOR=true + +## NewRelic +# https://docs.newrelic.com/docs/agents/ruby-agent/configuration/ruby-agent-configuration/ +# NEW_RELIC_LICENSE_KEY= +# Set this to true to allow newrelic apm to send logs. +# This is turned off by default. +# NEW_RELIC_APPLICATION_LOGGING_ENABLED= + +## Datadog +## https://github.com/DataDog/dd-trace-rb/blob/master/docs/GettingStarted.md#environment-variables +# DD_TRACE_AGENT_URL= + +## IP look up configuration +## ref https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md +## works only on accounts with ip look up feature enabled +# IP_LOOKUP_SERVICE=geoip2 +# maxmindb api key to use geoip2 service +# IP_LOOKUP_API_KEY= + +## Rack Attack configuration +## To prevent and throttle abusive requests +# ENABLE_RACK_ATTACK=true + +## Running chatwoot as an API only server +## setting this value to true will disable the frontend dashboard endpoints +# CW_API_ONLY_SERVER=false + +## Development Only Config +# if you want to use letter_opener for local emails +# LETTER_OPENER=true +# meant to be used in github codespaces +# WEBPACKER_DEV_SERVER_PUBLIC= + +# If you want to use official mobile app, +# the notifications would be relayed via a Chatwoot server +ENABLE_PUSH_RELAY_SERVER=true + +# Stripe API key +STRIPE_SECRET_KEY= +STRIPE_WEBHOOK_SECRET= + +# Set to true if you want to upload files to cloud storage using the signed url +# Make sure to follow https://edgeguides.rubyonrails.org/active_storage_overview.html#cross-origin-resource-sharing-cors-configuration on the cloud storage after setting this to true. +DIRECT_UPLOADS_ENABLED= + diff --git a/.cw.env.template b/.cw.env.template new file mode 100644 index 0000000..0049535 --- /dev/null +++ b/.cw.env.template @@ -0,0 +1,208 @@ +# Used to verify the integrity of signed cookies. so ensure a secure value is set +SECRET_KEY_BASE='4ZzW8MpYUkw2hWf4ZzW8MpYUkw2hWf4ZzW8MpYUkw2hWf' + +# Replace with the URL you are planning to use for your app +FRONTEND_URL=http://0.0.0.0:3000 + +# If the variable is set, all non-authenticated pages would fallback to the default locale. +# Whenever a new account is created, the default language will be DEFAULT_LOCALE instead of en +# DEFAULT_LOCALE=en + +# If you plan to use CDN for your assets, set Asset CDN Host +ASSET_CDN_HOST= + +# Force all access to the app over SSL, default is set to false +FORCE_SSL=false + +# This lets you control new sign ups on your chatwoot installation +# true : default option, allows sign ups +# false : disables all the end points related to sign ups +# api_only: disables the UI for signup, but you can create sign ups via the account apis +ENABLE_ACCOUNT_SIGNUP=false + +# Redis config +REDIS_URL=redis://redis:6379 +# If you are using docker-compose, set this variable's value to be any string, +# which will be the password for the redis service running inside the docker-compose +# to make it secure +REDIS_PASSWORD='qwer1234' +# Redis Sentinel can be used by passing list of sentinel host and ports e,g. sentinel_host1:port1,sentinel_host2:port2 +REDIS_SENTINELS= +# Redis sentinel master name is required when using sentinel, default value is "mymaster". +# You can find list of master using "SENTINEL masters" command +REDIS_SENTINEL_MASTER_NAME= + +# Redis premium breakage in heroku fix +# enable the following configuration +# ref: https://github.com/chatwoot/chatwoot/issues/2420 +# REDIS_OPENSSL_VERIFY_MODE=none + +# Postgres Database config variables +# You can leave POSTGRES_DATABASE blank. The default name of +# the database in the production environment is chatwoot_production +# POSTGRES_DATABASE= +POSTGRES_HOST=postgres +POSTGRES_USERNAME=postgres +POSTGRES_PASSWORD='qwer1234' +RAILS_ENV=development +RAILS_MAX_THREADS=5 + +# The email from which all outgoing emails are sent +# could user either `email@yourdomain.com` or `BrandName ` +MAILER_SENDER_EMAIL="Sy Sang " + +#SMTP domain key is set up for HELO checking +SMTP_DOMAIN=chatwoot.com +# the default value is set "mailhog" and is used by docker-compose for development environments, +# Set the value as "localhost" or your SMTP address in other environments +SMTP_ADDRESS=mailhog +SMTP_PORT=1025 +SMTP_USERNAME= +SMTP_PASSWORD= +# plain,login,cram_md5 +SMTP_AUTHENTICATION= +SMTP_ENABLE_STARTTLS_AUTO=true +# Can be: 'none', 'peer', 'client_once', 'fail_if_no_peer_cert', see http://api.rubyonrails.org/classes/ActionMailer/Base.html +SMTP_OPENSSL_VERIFY_MODE=peer +# Comment out the following environment variables if required by your SMTP server +# SMTP_TLS= +# SMTP_SSL= + +# Mail Incoming +# This is the domain set for the reply emails when conversation continuity is enabled +MAILER_INBOUND_EMAIL_DOMAIN= +# Set this to appropriate ingress channel with regards to incoming emails +# Possible values are : +# relay for Exim, Postfix, Qmail +# mailgun for Mailgun +# mandrill for Mandrill +# postmark for Postmark +# sendgrid for Sendgrid +RAILS_INBOUND_EMAIL_SERVICE= +# Use one of the following based on the email ingress service +# Ref: https://edgeguides.rubyonrails.org/action_mailbox_basics.html +RAILS_INBOUND_EMAIL_PASSWORD= +MAILGUN_INGRESS_SIGNING_KEY= +MANDRILL_INGRESS_API_KEY= + +# Storage +ACTIVE_STORAGE_SERVICE=local + +# Amazon S3 +# documentation: https://www.chatwoot.com/docs/configuring-s3-bucket-as-cloud-storage +S3_BUCKET_NAME= +AWS_ACCESS_KEY_ID= +AWS_SECRET_ACCESS_KEY= +AWS_REGION= + +# Log settings +# Disable if you want to write logs to a file +RAILS_LOG_TO_STDOUT=true +LOG_LEVEL=info +LOG_SIZE=500 + +### This environment variables are only required if you are setting up social media channels + +# Facebook +# documentation: https://www.chatwoot.com/docs/facebook-setup +FB_VERIFY_TOKEN= +FB_APP_SECRET= +FB_APP_ID= + +# https://developers.facebook.com/docs/messenger-platform/instagram/get-started#app-dashboard +IG_VERIFY_TOKEN= + +# Twitter +# documentation: https://www.chatwoot.com/docs/twitter-app-setup +TWITTER_APP_ID= +TWITTER_CONSUMER_KEY= +TWITTER_CONSUMER_SECRET= +TWITTER_ENVIRONMENT= + +#slack integration +SLACK_CLIENT_ID= +SLACK_CLIENT_SECRET= + +### Change this env variable only if you are using a custom build mobile app +## Mobile app env variables +IOS_APP_ID=L7YLMN4634.com.chatwoot.app +ANDROID_BUNDLE_ID=com.chatwoot.app + +# https://developers.google.com/android/guides/client-auth (use keytool to print the fingerprint in the first section) +ANDROID_SHA256_CERT_FINGERPRINT=AC:73:8E:DE:EB:56:EA:CC:10:87:02:A7:65:37:7B:38:D4:5D:D4:53:F8:3B:FB:D3:C6:28:64:1D:AA:08:1E:D8 + +### Smart App Banner +# https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/PromotingAppswithAppBanners/PromotingAppswithAppBanners.html +# You can find your app-id in https://itunesconnect.apple.com +#IOS_APP_IDENTIFIER=1495796682 + +## Push Notification +## generate a new key value here : https://d3v.one/vapid-key-generator/ +# VAPID_PUBLIC_KEY= +# VAPID_PRIVATE_KEY= +# +# for mobile apps +# FCM_SERVER_KEY= + +## Bot Customizations +USE_INBOX_AVATAR_FOR_BOT=true + +### APM and Error Monitoring configurations +## Elastic APM +## https://www.elastic.co/guide/en/apm/agent/ruby/current/getting-started-rails.html +# ELASTIC_APM_SERVER_URL= +# ELASTIC_APM_SECRET_TOKEN= + +## Sentry +# SENTRY_DSN= + +## Scout +## https://scoutapm.com/docs/ruby/configuration +# SCOUT_KEY=YOURKEY +# SCOUT_NAME=YOURAPPNAME (Production) +# SCOUT_MONITOR=true + +## NewRelic +# https://docs.newrelic.com/docs/agents/ruby-agent/configuration/ruby-agent-configuration/ +# NEW_RELIC_LICENSE_KEY= +# Set this to true to allow newrelic apm to send logs. +# This is turned off by default. +# NEW_RELIC_APPLICATION_LOGGING_ENABLED= + +## Datadog +## https://github.com/DataDog/dd-trace-rb/blob/master/docs/GettingStarted.md#environment-variables +# DD_TRACE_AGENT_URL= + +## IP look up configuration +## ref https://github.com/alexreisner/geocoder/blob/master/README_API_GUIDE.md +## works only on accounts with ip look up feature enabled +# IP_LOOKUP_SERVICE=geoip2 +# maxmindb api key to use geoip2 service +# IP_LOOKUP_API_KEY= + +## Rack Attack configuration +## To prevent and throttle abusive requests +# ENABLE_RACK_ATTACK=true + +## Running chatwoot as an API only server +## setting this value to true will disable the frontend dashboard endpoints +# CW_API_ONLY_SERVER=false + +## Development Only Config +# if you want to use letter_opener for local emails +# LETTER_OPENER=true +# meant to be used in github codespaces +# WEBPACKER_DEV_SERVER_PUBLIC= + +# If you want to use official mobile app, +# the notifications would be relayed via a Chatwoot server +ENABLE_PUSH_RELAY_SERVER=true + +# Stripe API key +STRIPE_SECRET_KEY= +STRIPE_WEBHOOK_SECRET= + +# Set to true if you want to upload files to cloud storage using the signed url +# Make sure to follow https://edgeguides.rubyonrails.org/active_storage_overview.html#cross-origin-resource-sharing-cors-configuration on the cloud storage after setting this to true. +DIRECT_UPLOADS_ENABLED= + diff --git a/.gitignore b/.gitignore index 48cd5be..f1b2bd1 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,8 @@ botserver-app/auth/ botserver-app/git/ botserver-app/logs/ botserver-app/models/ +botserver-app/credentials.yml botfrontend/botfrontend/local.py .env +.cw.env diff --git a/botfrontend/chatroom/templates/chatroom/index.html b/botfrontend/chatroom/templates/chatroom/index.html index 404b121..f422254 100644 --- a/botfrontend/chatroom/templates/chatroom/index.html +++ b/botfrontend/chatroom/templates/chatroom/index.html @@ -21,16 +21,14 @@ (e.async = !0), (e.onload = () => { window.WebChat.default({ - socketUrl: "{{ socketUrl }}", - // add other props here - - - - - - - - + customData:{language:"en"}, + socketUrl:"ws://cs.rasachatbot.sysang/cable", + protocol: 'sockcw', + withRules: true, + protocolOptions:{ + inboxIdentifier: "8pcVNHNn5Nc1cYZy1kGSsXjG", + chatwootAPIUrl: "http://cs.rasachatbot.sysang/public/api/v1/", + }, }, null); }), t.insertBefore(e, t.firstChild); diff --git a/botserver-app/addons/channels/chatwoot.py b/botserver-app/addons/channels/chatwoot.py index fbd01ce..bec49bd 100644 --- a/botserver-app/addons/channels/chatwoot.py +++ b/botserver-app/addons/channels/chatwoot.py @@ -1,7 +1,6 @@ import asyncio import inspect import logging -import json from sanic import Sanic, Blueprint, response from sanic.request import Request @@ -55,10 +54,10 @@ def select_output_channel(self, channel, cfg, **kwargs): out_channel = None if channel == 'cwwebsite': out_channel = CwwebsiteOutput( - chatwoot_url=cfg.chatwoot_url, - bot_token=cfg.bot_token, - botagent_account_id=cfg.botagent_account_id, - conversation_id=kwargs.conversation_id, + chatwoot_url=self.chatwoot_url, + bot_token=cfg.get("bot_token"), + botagent_account_id=cfg.get("botagent_account_id"), + conversation_id=kwargs.get("conversation_id"), ) return out_channel @@ -74,19 +73,21 @@ def blueprint( ) async def handler(request: Request) -> HTTPResponse: - cfg = getattr(self, request.ctx.configuration_name) + cfg = getattr(self, request.route.ctx.configuration_name) message = request.json + logger.info('[DEV] message: %s', message) metadata = self.get_metadata(request) if self._check_should_proceed_message(message): sender = message.get("sender", {}) sender_id = sender.get('id', None) content = message.get("content", None) + conversation = message.get('conversation', {}) conversation_id = conversation.get('id', None) - input_channel = cfg.sub_channel + input_channel = cfg.get("sub_channel") collector = CollectingOutputChannel() - out_channel = self.select_output_channel( + output_channel = self.select_output_channel( channel=input_channel, cfg=cfg, conversation_id=conversation_id, @@ -98,23 +99,20 @@ async def handler(request: Request) -> HTTPResponse: UserMessage( text=content, input_channel=input_channel, - output_channel=collector, + output_channel=output_channel, sender_id=sender_id, metadata=metadata, ) ) - for message in collector.messages: - await out_channel.send_response(message) + # for message in collector.messages: + # await output_channel.send_response(message) except CancelledError: logger.error( - f"Message handling timed out for " f"user message '{text}'." - ) + f"Message handling timed out for message: %s", message) except Exception: - logger.exception( - f"An exception occured while handling " - f"user message '{text}'.") + logger.exception(f"An exception occured while handling message: %s", message) return response.text("", status=204) diff --git a/botserver-app/addons/channels/cwwebsite_output.py b/botserver-app/addons/channels/cwwebsite_output.py index 2881915..d350fb9 100644 --- a/botserver-app/addons/channels/cwwebsite_output.py +++ b/botserver-app/addons/channels/cwwebsite_output.py @@ -1,4 +1,5 @@ import requests +import json from typing import Text, Dict, Any, Optional, Callable, Awaitable, NoReturn, List, Iterable @@ -10,7 +11,7 @@ def name(cls) -> Text: """Every output channel needs a name to identify it.""" return cls.__name__ - async def send_response(self, message: Dict[Text, Any]) -> None: + async def send_response(self, recipient_id: Text, message: Dict[Text, Any]) -> None: """Send a message to the client.""" if message.get("quick_replies"): diff --git a/botserver-app/credentials.yml b/botserver-app/credentials.template.yml similarity index 100% rename from botserver-app/credentials.yml rename to botserver-app/credentials.template.yml diff --git a/deployment_note.md b/deployment_note.md index b85937d..2686c29 100644 --- a/deployment_note.md +++ b/deployment_note.md @@ -66,3 +66,14 @@ for tracker_state, label in zip(tracker_state_features, label_ids): - issue: https://github.com/RasaHQ/rasa/issues/11061 - advise: https://github.com/RasaHQ/rasa/issues/11061#issuecomment-1119870053 - `nvim /opt/venv/lib/python3.8/site-packages/rasa/shared/constants.py`, DEFAULT_SESSION_EXPIRATION_TIME_IN_MINUTES -> False + +# chatwoot +- Be for running `docker compose up -d` prepare the database by running the migrations by `docker compose run --rm rails bundle exec rails db:chatwoot_prepare` +- Access Rails console, `docker exec -it chatwoot_rails_1 bundle exec rails c` +- (optional) `chmod 777 -R mounts/cw/storage` +- (optional) `chmod 777 -R mounts/cwdb` +- (optional) `rm -rf mounts/cwdb/*` +- Add AgentBot: https://www.chatwoot.com/docs/product/others/agent-bots +> `bot = AgentBot.create!(name:"Rasa Chatbot", outgoing_url:"http://rasachatbot.sysang/webhooks/chatwoot/cwwebsite")` +> `bot.access_token.token` +> `AgentBotInbox.create!(inbox: Inbox.find(1), agent_bot: bot)` diff --git a/docker-compose.yml b/docker-compose.yml index a9e8548..4e04ed2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,9 +3,9 @@ version: "3.4" x-database-credentials: &database-credentials DB_HOST: "db" DB_PORT: "5432" - DB_USER: "${DB_USER:-admin}" + DB_USER: "${DB_USER}" DB_PASSWORD: "${DB_PASSWORD}" - DB_LOGIN_DB: "${DB_LOGIN_DB:-rasa}" + DB_LOGIN_DB: "${DB_DATABASE}" x-rabbitmq-credentials: &rabbitmq-credentials RABBITMQ_HOST: "rabbit" @@ -37,7 +37,7 @@ x-rasax-credentials: &rasax-credentials JWT_SECRET: ${JWT_SECRET} RASA_USER_APP: "http://action-server:5055" RASA_PRODUCTION_HOST: "http://rasa-production:5005" - RASA_WORKER_HOST: "http://rasa-worker:5005" + # RASA_WORKER_HOST: "http://rasa-worker:5005" RASA_TOKEN: ${RASA_TOKEN} x-rasa-credentials: &rasa-credentials @@ -94,8 +94,8 @@ services: <<: *database-credentials <<: *rasa-credentials SELF_PORT: "5002" - DB_DATABASE: "${DB_DATABASE:-rasa}" RASA_MODEL_DIR: "/app/models" + DB_DATABASE: "${DB_DATABASE}" PASSWORD_SALT: ${PASSWORD_SALT} RABBITMQ_QUEUE: "rasa_production_events" RASA_X_USER_ANALYTICS: "0" @@ -119,6 +119,7 @@ services: - "8000" environment: <<: *database-credentials + DB_DATABASE: "${DB_DATABASE}" RUN_DATABASE_MIGRATION_AS_SEPARATE_SERVICE: "true" MPLCONFIGDIR: "/tmp/.matplotlib" depends_on: @@ -135,14 +136,16 @@ services: MPLCONFIGDIR: "/tmp/.matplotlib" RASA_MODEL_SERVER: "http://rasa-x:5002/api/projects/default/models/tags/production" - rasa-worker: - <<: *default-rasa-service - environment: - <<: *rasa-credentials - RASA_ENVIRONMENT: "worker" - DB_DATABASE: "worker_tracker" - MPLCONFIGDIR: "/tmp/.matplotlib" - RASA_MODEL_SERVER: "http://rasa-x:5002/api/projects/default/models/tags/production" + # rasa-worker: + # <<: *default-rasa-service + # volumes: + # - ./botserver-app/addons:/app/addons + # environment: + # <<: *rasa-credentials + # RASA_ENVIRONMENT: "worker" + # DB_DATABASE: "worker_tracker" + # MPLCONFIGDIR: "/tmp/.matplotlib" + # RASA_MODEL_SERVER: "http://rasa-x:5002/api/projects/default/models/tags/production" # deploy: # resources: # reservations: @@ -177,11 +180,11 @@ services: restart: on-failure:5 image: "bitnami/postgresql:11.9.0" expose: - - "5432" + - "5432:54321" environment: - POSTGRESQL_USERNAME: "${DB_USER:-admin}" + POSTGRESQL_USERNAME: "${DB_USER}" POSTGRESQL_PASSWORD: "${DB_PASSWORD}" - POSTGRESQL_DATABASE: "${DB_DATABASE:-rasa}" + POSTGRESQL_DATABASE: "${DB_DATABASE}" volumes: - ./mounts/db:/bitnami/postgresql @@ -223,7 +226,7 @@ services: depends_on: - rasa-x - rasa-production - - rasa-worker + # - rasa-worker - botfrontend redis: @@ -237,9 +240,57 @@ services: botfrontend: restart: on-failure:5 image: "sysang/botfrontend" - build: + build: context: "./botfrontend" volumes: - ./botfrontend/:/usr/src/app/ expose: - "8000" + + cwbase: &cwbase + image: chatwoot/chatwoot:v2.8.1-ce + env_file: .cw.env + volumes: + - ./mounts/cw/storage:/app/storage + tty: true + stdin_open: true + + rails: + <<: *cwbase + depends_on: + - cwdb + - redis + # ports: + # - '3000:3000' + # expose: + # - "3000" + environment: + - NODE_ENV=production + - RAILS_ENV=production + - INSTALLATION_ENV=docker + entrypoint: docker/entrypoints/rails.sh + # command: ['bundle', 'exec', 'rails', 's', '-p', '3000', '-b', '127.0.0.1'] + command: ['bundle', 'exec', 'rails', 's', '-p', '3000'] + + sidekiq: + <<: *cwbase + depends_on: + - cwdb + - redis + environment: + - NODE_ENV=production + - RAILS_ENV=production + - INSTALLATION_ENV=docker + command: ['bundle', 'exec', 'sidekiq', '-C', 'config/sidekiq.yml'] + + cwdb: + restart: on-failure:5 + image: "bitnami/postgresql:11.9.0" + expose: + - "5432:54322" + environment: + POSTGRESQL_USERNAME: "${POSTGRES_CWUSER}" + POSTGRESQL_PASSWORD: "${POSTGRES_CWPASSWORD}" + POSTGRESQL_DATABASE: "${POSTGRES_CWDB}" + volumes: + - ./mounts/cwdb:/bitnami/postgresql diff --git a/docker/entrypoints/rails.sh b/docker/entrypoints/rails.sh new file mode 100644 index 0000000..77657f6 --- /dev/null +++ b/docker/entrypoints/rails.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +set -x + +# Remove a potentially pre-existing server.pid for Rails. +rm -rf /app/tmp/pids/server.pid +rm -rf /app/tmp/cache/* + +echo "Waiting for postgres to become ready...." + +# Let DATABASE_URL env take presedence over individual connection params. +# This is done to avoid printing the DATABASE_URL in the logs +$(docker/entrypoints/helpers/pg_database_url.rb) +PG_READY="pg_isready -h $POSTGRES_HOST -p $POSTGRES_PORT -U $POSTGRES_USERNAME" + +until $PG_READY +do + sleep 2; +done + +echo "Database ready to accept connections." + +#install missing gems for local dev as we are using base image compiled for production +bundle install + +BUNDLE="bundle check" + +until $BUNDLE +do + sleep 2; +done + +# Execute the main process of the container +exec "$@"