diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f054518 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +.idea +.git +examples \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE new file mode 100644 index 0000000..a275c4f --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE @@ -0,0 +1,42 @@ + + + + + + + + + + +- [ ] If this pull request closes/resolves/fixes an existing issue, replace the issue url. Closes: +- [ ] Update the [`CHANGELOG.md`](https://github.com/apache/skywalking-ruby/blob/main/CHANGELOG.md). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a4faccf..c7bac90 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,43 +23,48 @@ on: - main tags: - 'v*' - schedule: - - cron: '0 18 * * *' concurrency: - group: CI-plugin-e2e-${{ github.event.pull_request.number || github.ref }} + group: ci-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: - build: + build-and-check: runs-on: ubuntu-latest - name: Ruby ${{ matrix.ruby }} + name: Ruby ${{ matrix.ruby-version }} | Build and Check + timeout-minutes: 60 strategy: - fail-fast: true + fail-fast: false matrix: - ruby: - - 3.2 + ruby-version: [ 3.0 ] steps: - - name: Set up Ruby + - name: Checkout source codes + uses: actions/checkout@v4 + with: + submodules: true + - name: Set up Ruby ${{ matrix.ruby-version }} uses: ruby/setup-ruby@v1 with: - ruby-version: ${{ matrix.ruby }} - bundler-cache: true - - name: Run Bundler + ruby-version: ${{ matrix.ruby-version }} + - name: Check License + uses: apache/skywalking-eyes/header@3ea9df11bb3a5a85665377d1fd10c02edecf2c40 + - name: Install system dependency run: | gem install bundler - bundle --version + bundler install + - name: RuboCop Linter + run: bundler exec rubocop CheckStatus: if: always() needs: - - build + - build-and-check runs-on: ubuntu-latest timeout-minutes: 10 steps: - name: Merge Requirement run: | - if [[ ${{ needs.build.result }} != 'success' ]]; then + if [[ ${{ needs.build-and-check.result }} != 'success' ]]; then exit -1 fi \ No newline at end of file diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000..167c13f --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,73 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: e2e + +on: + pull_request: + push: + branches: + - main + +concurrency: + group: e2e-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + prep-build-plugin: + name: Build matrix + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + plugins: ${{ steps.plugins.outputs.plugins }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - id: plugins + run: echo "plugins=$(ls spec/scenarios | grep -v common | jq --raw-input | jq --slurp --compact-output)" >> "$GITHUB_OUTPUT" + + e2e-test: + name: Run E2E Tests | ${{ matrix.plugin }} | Ruby ${{ matrix.ruby-version }} + runs-on: ubuntu-latest + timeout-minutes: 90 + needs: [ prep-build-plugin ] + strategy: + matrix: + plugin: ${{ fromJson(needs.prep-build-plugin.outputs.plugins) }} + ruby-version: [ "3.0" ] + env: + SW_RUBY_VERSION: ${{ matrix.ruby-version }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - name: Set up Ruby ${{ matrix.ruby-version }} + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby-version }} + - name: Install docker-compose + shell: bash + run: | + if ! command docker-compose 2>&1 > /dev/null; then + echo "Installing docker-compose" + sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose + sudo chmod +x /usr/local/bin/docker-compose + fi + - name: Run E2E tests + run: | + gem install bundler && bundle + bundle exec rspec spec/scenarios/${{ matrix.plugin }} \ No newline at end of file diff --git a/.github/workflows/publish-docker.yaml b/.github/workflows/publish-docker.yaml new file mode 100644 index 0000000..da211a5 --- /dev/null +++ b/.github/workflows/publish-docker.yaml @@ -0,0 +1,49 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +name: publish-docker + +on: + push: + branches: + - main + +env: + HUB: ghcr.io/apache/skywalking-ruby + +jobs: + build: + if: github.repository == 'apache/skywalking-ruby' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + timeout-minutes: 150 + env: + VERSION: ${{ github.sha }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + - name: Log in to the Container registry + uses: docker/login-action@v1.10.0 + with: + registry: ${{ env.HUB }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Polish docker image + run: | + make docker.push || make docker.push diff --git a/.gitignore b/.gitignore index 869e48b..1d7e3d2 100644 --- a/.gitignore +++ b/.gitignore @@ -76,4 +76,5 @@ build-iPhoneSimulator/ # .rubocop-https?--* Gemfile.lock gemfiles/*.lock -.DS_Store! \ No newline at end of file +.DS_Store! +spec/workspace \ No newline at end of file diff --git a/.licenserc.yaml b/.licenserc.yaml new file mode 100644 index 0000000..97abd75 --- /dev/null +++ b/.licenserc.yaml @@ -0,0 +1,36 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +header: + license: + spdx-id: Apache-2.0 + copyright-owner: Apache Software Foundation + + paths-ignore: + - 'licenses' + - '**/*.md' + - 'LICENSE' + - 'NOTICE' + - '.github/PULL_REQUEST_TEMPLATE' + - '**/.gitignore' + - '.gitmodules' + - 'lib/skywalking/proto/**' + - 'examples/**' + - '.rspec' + + comment: on-failure diff --git a/.rspec b/.rspec index 34c5164..210a1d6 100644 --- a/.rspec +++ b/.rspec @@ -1,3 +1,2 @@ --format documentation ---color ---require spec_helper +--color \ No newline at end of file diff --git a/.rubocop.yml b/.rubocop.yml index c31caae..7e38de8 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -124,6 +124,12 @@ Style/SymbolProc: Style/ExplicitBlockArgument: Enabled: false +Style/ClassVars: + Enabled: false + +Style/CombinableDefined: + Enabled: false + ##### # Lint ##### diff --git a/CHANGELOG.md b/CHANGELOG.md index af0fe1b..e1bbbe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,12 @@ Release Notes. ------------------ #### Features - Initialize the ruby agent core. +- Implement e2e tests. #### Plugins * Support [Sinatra](https://github.com/sinatra/sinatra) * Support [redis-rb](https://github.com/redis/redis-rb) +* Support [net-http](https://github.com/ruby/net-http) #### Documentation * Initialize the documentation. \ No newline at end of file diff --git a/NOTICE b/NOTICE index 04d6ba5..636e417 100644 --- a/NOTICE +++ b/NOTICE @@ -1,5 +1,5 @@ Apache SkyWalking -Copyright 2017-2024 The Apache Software Foundation +Copyright 2017-2025 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..650dd1e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,7 @@ +# SkyWalking Ruby Agent + +**This is the official documentation of SkyWalking Ruby agent. Welcome to the SkyWalking community!** + +SkyWalking Ruby is an open-source auto-instrument agent that provides support for + +distributed tracing across different frameworks within the Ruby language. \ No newline at end of file diff --git a/docs/How-to-release.md b/docs/en/development-and-contribution/how-to-release.md similarity index 98% rename from docs/How-to-release.md rename to docs/en/development-and-contribution/how-to-release.md index 2e531e4..143888a 100644 --- a/docs/How-to-release.md +++ b/docs/en/development-and-contribution/how-to-release.md @@ -5,7 +5,7 @@ This documentation guides the release manager to release the SkyWalking Ruby in ## Prerequisites 1. Close (if finished, or move to next milestone otherwise) all issues in the current milestone from [skywalking-ruby](https://github.com/apache/skywalking-ruby/milestones) and [skywalking](https://github.com/apache/skywalking/milestones), create a new milestone for the next release. -1. Update [CHANGELOG.md](../CHANGELOG.md) and `version` in [Version.rb](../lib/skywalking/version.rb). +1. Update [CHANGELOG.md](../../../CHANGELOG.md) and `version` in [Version.rb](../../../lib/skywalking/version.rb). ## Add your GPG public key to Apache svn diff --git a/examples/rails-demo/app/assets/images/.keep b/docs/en/setup/configuration.md similarity index 100% rename from examples/rails-demo/app/assets/images/.keep rename to docs/en/setup/configuration.md diff --git a/examples/rails-demo/app/controllers/concerns/.keep b/docs/en/setup/quick-start.md similarity index 100% rename from examples/rails-demo/app/controllers/concerns/.keep rename to docs/en/setup/quick-start.md diff --git a/examples/rails-demo/.dockerignore b/examples/rails-demo/.dockerignore deleted file mode 100644 index 7540593..0000000 --- a/examples/rails-demo/.dockerignore +++ /dev/null @@ -1,47 +0,0 @@ -# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. - -# Ignore git directory. -/.git/ -/.gitignore - -# Ignore bundler config. -/.bundle - -# Ignore all environment files. -/.env* - -# Ignore all default key files. -/config/master.key -/config/credentials/*.key - -# Ignore all logfiles and tempfiles. -/log/* -/tmp/* -!/log/.keep -!/tmp/.keep - -# Ignore pidfiles, but keep the directory. -/tmp/pids/* -!/tmp/pids/.keep - -# Ignore storage (uploaded files in development and any SQLite databases). -/storage/* -!/storage/.keep -/tmp/storage/* -!/tmp/storage/.keep - -# Ignore assets. -/node_modules/ -/app/assets/builds/* -!/app/assets/builds/.keep -/public/assets - -# Ignore CI service files. -/.github - -# Ignore development files -/.devcontainer - -# Ignore Docker-related files -/.dockerignore -/Dockerfile* diff --git a/examples/rails-demo/.gitattributes b/examples/rails-demo/.gitattributes deleted file mode 100644 index 8dc4323..0000000 --- a/examples/rails-demo/.gitattributes +++ /dev/null @@ -1,9 +0,0 @@ -# See https://git-scm.com/docs/gitattributes for more about git attribute files. - -# Mark the database schema as having been generated. -db/schema.rb linguist-generated - -# Mark any vendored files as having been vendored. -vendor/* linguist-vendored -config/credentials/*.yml.enc diff=rails_credentials -config/credentials.yml.enc diff=rails_credentials diff --git a/examples/rails-demo/.gitignore b/examples/rails-demo/.gitignore deleted file mode 100644 index f92525c..0000000 --- a/examples/rails-demo/.gitignore +++ /dev/null @@ -1,34 +0,0 @@ -# See https://help.github.com/articles/ignoring-files for more about ignoring files. -# -# Temporary files generated by your text editor or operating system -# belong in git's global ignore instead: -# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` - -# Ignore bundler config. -/.bundle - -# Ignore all environment files. -/.env* - -# Ignore all logfiles and tempfiles. -/log/* -/tmp/* -!/log/.keep -!/tmp/.keep - -# Ignore pidfiles, but keep the directory. -/tmp/pids/* -!/tmp/pids/ -!/tmp/pids/.keep - -# Ignore storage (uploaded files in development and any SQLite databases). -/storage/* -!/storage/.keep -/tmp/storage/* -!/tmp/storage/ -!/tmp/storage/.keep - -/public/assets - -# Ignore master key for decrypting credentials and more. -/config/master.key diff --git a/examples/rails-demo/.kamal/hooks/docker-setup.sample b/examples/rails-demo/.kamal/hooks/docker-setup.sample deleted file mode 100755 index 2fb07d7..0000000 --- a/examples/rails-demo/.kamal/hooks/docker-setup.sample +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -echo "Docker set up on $KAMAL_HOSTS..." diff --git a/examples/rails-demo/.kamal/hooks/post-deploy.sample b/examples/rails-demo/.kamal/hooks/post-deploy.sample deleted file mode 100755 index 75efafc..0000000 --- a/examples/rails-demo/.kamal/hooks/post-deploy.sample +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh - -# A sample post-deploy hook -# -# These environment variables are available: -# KAMAL_RECORDED_AT -# KAMAL_PERFORMER -# KAMAL_VERSION -# KAMAL_HOSTS -# KAMAL_ROLE (if set) -# KAMAL_DESTINATION (if set) -# KAMAL_RUNTIME - -echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/examples/rails-demo/.kamal/hooks/post-proxy-reboot.sample b/examples/rails-demo/.kamal/hooks/post-proxy-reboot.sample deleted file mode 100755 index 1435a67..0000000 --- a/examples/rails-demo/.kamal/hooks/post-proxy-reboot.sample +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/examples/rails-demo/.kamal/hooks/pre-build.sample b/examples/rails-demo/.kamal/hooks/pre-build.sample deleted file mode 100755 index f87d811..0000000 --- a/examples/rails-demo/.kamal/hooks/pre-build.sample +++ /dev/null @@ -1,51 +0,0 @@ -#!/bin/sh - -# A sample pre-build hook -# -# Checks: -# 1. We have a clean checkout -# 2. A remote is configured -# 3. The branch has been pushed to the remote -# 4. The version we are deploying matches the remote -# -# These environment variables are available: -# KAMAL_RECORDED_AT -# KAMAL_PERFORMER -# KAMAL_VERSION -# KAMAL_HOSTS -# KAMAL_ROLE (if set) -# KAMAL_DESTINATION (if set) - -if [ -n "$(git status --porcelain)" ]; then - echo "Git checkout is not clean, aborting..." >&2 - git status --porcelain >&2 - exit 1 -fi - -first_remote=$(git remote) - -if [ -z "$first_remote" ]; then - echo "No git remote set, aborting..." >&2 - exit 1 -fi - -current_branch=$(git branch --show-current) - -if [ -z "$current_branch" ]; then - echo "Not on a git branch, aborting..." >&2 - exit 1 -fi - -remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) - -if [ -z "$remote_head" ]; then - echo "Branch not pushed to remote, aborting..." >&2 - exit 1 -fi - -if [ "$KAMAL_VERSION" != "$remote_head" ]; then - echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 - exit 1 -fi - -exit 0 diff --git a/examples/rails-demo/.kamal/hooks/pre-connect.sample b/examples/rails-demo/.kamal/hooks/pre-connect.sample deleted file mode 100755 index 18e61d7..0000000 --- a/examples/rails-demo/.kamal/hooks/pre-connect.sample +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env ruby - -# A sample pre-connect check -# -# Warms DNS before connecting to hosts in parallel -# -# These environment variables are available: -# KAMAL_RECORDED_AT -# KAMAL_PERFORMER -# KAMAL_VERSION -# KAMAL_HOSTS -# KAMAL_ROLE (if set) -# KAMAL_DESTINATION (if set) -# KAMAL_RUNTIME - -hosts = ENV["KAMAL_HOSTS"].split(",") -results = nil -max = 3 - -elapsed = Benchmark.realtime do - results = hosts.map do |host| - Thread.new do - tries = 1 - - begin - Socket.getaddrinfo(host, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) - rescue SocketError - if tries < max - puts "Retrying DNS warmup: #{host}" - tries += 1 - sleep rand - retry - else - puts "DNS warmup failed: #{host}" - host - end - end - - tries - end - end.map(&:value) -end - -retries = results.sum - hosts.size -nopes = results.count { |r| r == max } - -puts "Prewarmed %d DNS lookups in %.2f sec: %d retries, %d failures" % [ hosts.size, elapsed, retries, nopes ] diff --git a/examples/rails-demo/.kamal/hooks/pre-deploy.sample b/examples/rails-demo/.kamal/hooks/pre-deploy.sample deleted file mode 100755 index 1b280c7..0000000 --- a/examples/rails-demo/.kamal/hooks/pre-deploy.sample +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env ruby - -# A sample pre-deploy hook -# -# Checks the Github status of the build, waiting for a pending build to complete for up to 720 seconds. -# -# Fails unless the combined status is "success" -# -# These environment variables are available: -# KAMAL_RECORDED_AT -# KAMAL_PERFORMER -# KAMAL_VERSION -# KAMAL_HOSTS -# KAMAL_COMMAND -# KAMAL_SUBCOMMAND -# KAMAL_ROLE (if set) -# KAMAL_DESTINATION (if set) - -# Only check the build status for production deployments -if ENV["KAMAL_COMMAND"] == "rollback" || ENV["KAMAL_DESTINATION"] != "production" - exit 0 -end - -require "bundler/inline" - -# true = install gems so this is fast on repeat invocations -gemfile(true, quiet: true) do - source "https://rubygems.org" - - gem "octokit" - gem "faraday-retry" -end - -MAX_ATTEMPTS = 72 -ATTEMPTS_GAP = 10 - -def exit_with_error(message) - $stderr.puts message - exit 1 -end - -class GithubStatusChecks - attr_reader :remote_url, :git_sha, :github_client, :combined_status - - def initialize - @remote_url = `git config --get remote.origin.url`.strip.delete_prefix("https://github.com/") - @git_sha = `git rev-parse HEAD`.strip - @github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) - refresh! - end - - def refresh! - @combined_status = github_client.combined_status(remote_url, git_sha) - end - - def state - combined_status[:state] - end - - def first_status_url - first_status = combined_status[:statuses].find { |status| status[:state] == state } - first_status && first_status[:target_url] - end - - def complete_count - combined_status[:statuses].count { |status| status[:state] != "pending"} - end - - def total_count - combined_status[:statuses].count - end - - def current_status - if total_count > 0 - "Completed #{complete_count}/#{total_count} checks, see #{first_status_url} ..." - else - "Build not started..." - end - end -end - - -$stdout.sync = true - -puts "Checking build status..." -attempts = 0 -checks = GithubStatusChecks.new - -begin - loop do - case checks.state - when "success" - puts "Checks passed, see #{checks.first_status_url}" - exit 0 - when "failure" - exit_with_error "Checks failed, see #{checks.first_status_url}" - when "pending" - attempts += 1 - end - - exit_with_error "Checks are still pending, gave up after #{MAX_ATTEMPTS * ATTEMPTS_GAP} seconds" if attempts == MAX_ATTEMPTS - - puts checks.current_status - sleep(ATTEMPTS_GAP) - checks.refresh! - end -rescue Octokit::NotFound - exit_with_error "Build status could not be found" -end diff --git a/examples/rails-demo/.kamal/hooks/pre-proxy-reboot.sample b/examples/rails-demo/.kamal/hooks/pre-proxy-reboot.sample deleted file mode 100755 index 061f805..0000000 --- a/examples/rails-demo/.kamal/hooks/pre-proxy-reboot.sample +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/examples/rails-demo/.kamal/secrets b/examples/rails-demo/.kamal/secrets deleted file mode 100644 index 9a771a3..0000000 --- a/examples/rails-demo/.kamal/secrets +++ /dev/null @@ -1,17 +0,0 @@ -# Secrets defined here are available for reference under registry/password, env/secret, builder/secrets, -# and accessories/*/env/secret in config/deploy.yml. All secrets should be pulled from either -# password manager, ENV, or a file. DO NOT ENTER RAW CREDENTIALS HERE! This file needs to be safe for git. - -# Example of extracting secrets from 1password (or another compatible pw manager) -# SECRETS=$(kamal secrets fetch --adapter 1password --account your-account --from Vault/Item KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY) -# KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD ${SECRETS}) -# RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY ${SECRETS}) - -# Use a GITHUB_TOKEN if private repositories are needed for the image -# GITHUB_TOKEN=$(gh config get -h github.com oauth_token) - -# Grab the registry password from ENV -KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD - -# Improve security by using a password manager. Never check config/master.key into git! -RAILS_MASTER_KEY=$(cat config/master.key) diff --git a/examples/rails-demo/.rubocop.yml b/examples/rails-demo/.rubocop.yml deleted file mode 100644 index f9d86d4..0000000 --- a/examples/rails-demo/.rubocop.yml +++ /dev/null @@ -1,8 +0,0 @@ -# Omakase Ruby styling for Rails -inherit_gem: { rubocop-rails-omakase: rubocop.yml } - -# Overwrite or add rules to create your own house style -# -# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` -# Layout/SpaceInsideArrayLiteralBrackets: -# Enabled: false diff --git a/examples/rails-demo/.ruby-version b/examples/rails-demo/.ruby-version deleted file mode 100644 index 9e79f6c..0000000 --- a/examples/rails-demo/.ruby-version +++ /dev/null @@ -1 +0,0 @@ -ruby-3.2.2 diff --git a/examples/rails-demo/Dockerfile b/examples/rails-demo/Dockerfile deleted file mode 100644 index 01f67a2..0000000 --- a/examples/rails-demo/Dockerfile +++ /dev/null @@ -1,72 +0,0 @@ -# syntax=docker/dockerfile:1 -# check=error=true - -# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: -# docker build -t app_demo . -# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name app_demo app_demo - -# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html - -# Make sure RUBY_VERSION matches the Ruby version in .ruby-version -ARG RUBY_VERSION=3.2.2 -FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base - -# Rails app lives here -WORKDIR /rails - -# Install base packages -RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y curl libjemalloc2 libvips sqlite3 && \ - rm -rf /var/lib/apt/lists /var/cache/apt/archives - -# Set production environment -ENV RAILS_ENV="production" \ - BUNDLE_DEPLOYMENT="1" \ - BUNDLE_PATH="/usr/local/bundle" \ - BUNDLE_WITHOUT="development" - -# Throw-away build stage to reduce size of final image -FROM base AS build - -# Install packages needed to build gems -RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y build-essential git pkg-config && \ - rm -rf /var/lib/apt/lists /var/cache/apt/archives - -# Install application gems -COPY Gemfile Gemfile.lock ./ -RUN bundle install && \ - rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ - bundle exec bootsnap precompile --gemfile - -# Copy application code -COPY . . - -# Precompile bootsnap code for faster boot times -RUN bundle exec bootsnap precompile app/ lib/ - -# Precompiling assets for production without requiring secret RAILS_MASTER_KEY -RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile - - - - -# Final stage for app image -FROM base - -# Copy built artifacts: gems, application -COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" -COPY --from=build /rails /rails - -# Run and own only the runtime files as a non-root user for security -RUN groupadd --system --gid 1000 rails && \ - useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \ - chown -R rails:rails db log storage tmp -USER 1000:1000 - -# Entrypoint prepares the database. -ENTRYPOINT ["/rails/bin/docker-entrypoint"] - -# Start server via Thruster by default, this can be overwritten at runtime -EXPOSE 80 -CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/examples/rails-demo/Gemfile b/examples/rails-demo/Gemfile deleted file mode 100644 index 2d308a9..0000000 --- a/examples/rails-demo/Gemfile +++ /dev/null @@ -1,64 +0,0 @@ -source "https://rubygems.org" - -# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" -gem "rails", "~> 8.0.0" -# The modern asset pipeline for Rails [https://github.com/rails/propshaft] -gem "propshaft" -# Use sqlite3 as the database for Active Record -gem "sqlite3", ">= 2.1" -# Use the Puma web server [https://github.com/puma/puma] -gem "puma", ">= 5.0" -# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] -gem "importmap-rails" -# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] -gem "turbo-rails" -# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] -gem "stimulus-rails" -# Build JSON APIs with ease [https://github.com/rails/jbuilder] -gem "jbuilder" -gem "async" -gem "grpc" -# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] -# gem "bcrypt", "~> 3.1.7" - -# Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem "tzinfo-data", platforms: %i[ windows jruby ] - -# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable -gem "solid_cache" -gem "solid_queue" -gem "solid_cable" - -# Reduces boot times through caching; required in config/boot.rb -gem "bootsnap", require: false - -# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] -gem "kamal", require: false - -# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] -gem "thruster", require: false - -# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] -# gem "image_processing", "~> 1.2" - -group :development, :test do - # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem - gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" - - # Static analysis for security vulnerabilities [https://brakemanscanner.org/] - gem "brakeman", require: false - - # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] - gem "rubocop-rails-omakase", require: false -end - -group :development do - # Use console on exceptions pages [https://github.com/rails/web-console] - gem "web-console" -end - -group :test do - # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] - gem "capybara" - gem "selenium-webdriver" -end diff --git a/examples/rails-demo/README.md b/examples/rails-demo/README.md index 7db80e4..0fda4c2 100644 --- a/examples/rails-demo/README.md +++ b/examples/rails-demo/README.md @@ -1,24 +1,9 @@ -# README +# rails-demo -This README would normally document whatever steps are necessary to get the -application up and running. +```ruby +# config/skywalking.rb -Things you may want to cover: +require 'skywalking' -* Ruby version - -* System dependencies - -* Configuration - -* Database creation - -* Database initialization - -* How to run the test suite - -* Services (job queues, cache servers, search engines, etc.) - -* Deployment instructions - -* ... +Skywalking.start +``` \ No newline at end of file diff --git a/examples/rails-demo/Rakefile b/examples/rails-demo/Rakefile deleted file mode 100644 index 9a5ea73..0000000 --- a/examples/rails-demo/Rakefile +++ /dev/null @@ -1,6 +0,0 @@ -# Add your own tasks in files placed in lib/tasks ending in .rake, -# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. - -require_relative "config/application" - -Rails.application.load_tasks diff --git a/examples/rails-demo/app/assets/stylesheets/application.css b/examples/rails-demo/app/assets/stylesheets/application.css deleted file mode 100644 index fe93333..0000000 --- a/examples/rails-demo/app/assets/stylesheets/application.css +++ /dev/null @@ -1,10 +0,0 @@ -/* - * This is a manifest file that'll be compiled into application.css. - * - * With Propshaft, assets are served efficiently without preprocessing steps. You can still include - * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard - * cascading order, meaning styles declared later in the document or manifest will override earlier ones, - * depending on specificity. - * - * Consider organizing styles into separate files for maintainability. - */ diff --git a/examples/rails-demo/app/controllers/application_controller.rb b/examples/rails-demo/app/controllers/application_controller.rb deleted file mode 100644 index 0d95db2..0000000 --- a/examples/rails-demo/app/controllers/application_controller.rb +++ /dev/null @@ -1,4 +0,0 @@ -class ApplicationController < ActionController::Base - # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. - allow_browser versions: :modern -end diff --git a/examples/rails-demo/app/helpers/application_helper.rb b/examples/rails-demo/app/helpers/application_helper.rb deleted file mode 100644 index de6be79..0000000 --- a/examples/rails-demo/app/helpers/application_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module ApplicationHelper -end diff --git a/examples/rails-demo/app/javascript/application.js b/examples/rails-demo/app/javascript/application.js deleted file mode 100644 index 0d7b494..0000000 --- a/examples/rails-demo/app/javascript/application.js +++ /dev/null @@ -1,3 +0,0 @@ -// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails -import "@hotwired/turbo-rails" -import "controllers" diff --git a/examples/rails-demo/app/javascript/controllers/application.js b/examples/rails-demo/app/javascript/controllers/application.js deleted file mode 100644 index 1213e85..0000000 --- a/examples/rails-demo/app/javascript/controllers/application.js +++ /dev/null @@ -1,9 +0,0 @@ -import { Application } from "@hotwired/stimulus" - -const application = Application.start() - -// Configure Stimulus development experience -application.debug = false -window.Stimulus = application - -export { application } diff --git a/examples/rails-demo/app/javascript/controllers/hello_controller.js b/examples/rails-demo/app/javascript/controllers/hello_controller.js deleted file mode 100644 index 5975c07..0000000 --- a/examples/rails-demo/app/javascript/controllers/hello_controller.js +++ /dev/null @@ -1,7 +0,0 @@ -import { Controller } from "@hotwired/stimulus" - -export default class extends Controller { - connect() { - this.element.textContent = "Hello World!" - } -} diff --git a/examples/rails-demo/app/javascript/controllers/index.js b/examples/rails-demo/app/javascript/controllers/index.js deleted file mode 100644 index 1156bf8..0000000 --- a/examples/rails-demo/app/javascript/controllers/index.js +++ /dev/null @@ -1,4 +0,0 @@ -// Import and register all your controllers from the importmap via controllers/**/*_controller -import { application } from "controllers/application" -import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" -eagerLoadControllersFrom("controllers", application) diff --git a/examples/rails-demo/app/jobs/application_job.rb b/examples/rails-demo/app/jobs/application_job.rb deleted file mode 100644 index d394c3d..0000000 --- a/examples/rails-demo/app/jobs/application_job.rb +++ /dev/null @@ -1,7 +0,0 @@ -class ApplicationJob < ActiveJob::Base - # Automatically retry jobs that encountered a deadlock - # retry_on ActiveRecord::Deadlocked - - # Most jobs are safe to ignore if the underlying records are no longer available - # discard_on ActiveJob::DeserializationError -end diff --git a/examples/rails-demo/app/mailers/application_mailer.rb b/examples/rails-demo/app/mailers/application_mailer.rb deleted file mode 100644 index 3c34c81..0000000 --- a/examples/rails-demo/app/mailers/application_mailer.rb +++ /dev/null @@ -1,4 +0,0 @@ -class ApplicationMailer < ActionMailer::Base - default from: "from@example.com" - layout "mailer" -end diff --git a/examples/rails-demo/app/models/application_record.rb b/examples/rails-demo/app/models/application_record.rb deleted file mode 100644 index b63caeb..0000000 --- a/examples/rails-demo/app/models/application_record.rb +++ /dev/null @@ -1,3 +0,0 @@ -class ApplicationRecord < ActiveRecord::Base - primary_abstract_class -end diff --git a/examples/rails-demo/app/models/concerns/.keep b/examples/rails-demo/app/models/concerns/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/app/views/layouts/application.html.erb b/examples/rails-demo/app/views/layouts/application.html.erb deleted file mode 100644 index 0752ccb..0000000 --- a/examples/rails-demo/app/views/layouts/application.html.erb +++ /dev/null @@ -1,28 +0,0 @@ - - - - <%= content_for(:title) || "App Demo" %> - - - - <%= csrf_meta_tags %> - <%= csp_meta_tag %> - - <%= yield :head %> - - <%# Enable PWA manifest for installable apps (make sure to enable in config/routes.rb too!) %> - <%#= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %> - - - - - - <%# Includes all stylesheet files in app/assets/stylesheets %> - <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> - <%= javascript_importmap_tags %> - - - - <%= yield %> - - diff --git a/examples/rails-demo/app/views/layouts/mailer.html.erb b/examples/rails-demo/app/views/layouts/mailer.html.erb deleted file mode 100644 index 3aac900..0000000 --- a/examples/rails-demo/app/views/layouts/mailer.html.erb +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - <%= yield %> - - diff --git a/examples/rails-demo/app/views/layouts/mailer.text.erb b/examples/rails-demo/app/views/layouts/mailer.text.erb deleted file mode 100644 index 37f0bdd..0000000 --- a/examples/rails-demo/app/views/layouts/mailer.text.erb +++ /dev/null @@ -1 +0,0 @@ -<%= yield %> diff --git a/examples/rails-demo/app/views/pwa/manifest.json.erb b/examples/rails-demo/app/views/pwa/manifest.json.erb deleted file mode 100644 index 5e654e3..0000000 --- a/examples/rails-demo/app/views/pwa/manifest.json.erb +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "AppDemo", - "icons": [ - { - "src": "/icon.png", - "type": "image/png", - "sizes": "512x512" - }, - { - "src": "/icon.png", - "type": "image/png", - "sizes": "512x512", - "purpose": "maskable" - } - ], - "start_url": "/", - "display": "standalone", - "scope": "/", - "description": "AppDemo.", - "theme_color": "red", - "background_color": "red" -} diff --git a/examples/rails-demo/app/views/pwa/service-worker.js b/examples/rails-demo/app/views/pwa/service-worker.js deleted file mode 100644 index b3a13fb..0000000 --- a/examples/rails-demo/app/views/pwa/service-worker.js +++ /dev/null @@ -1,26 +0,0 @@ -// Add a service worker for processing Web Push notifications: -// -// self.addEventListener("push", async (event) => { -// const { title, options } = await event.data.json() -// event.waitUntil(self.registration.showNotification(title, options)) -// }) -// -// self.addEventListener("notificationclick", function(event) { -// event.notification.close() -// event.waitUntil( -// clients.matchAll({ type: "window" }).then((clientList) => { -// for (let i = 0; i < clientList.length; i++) { -// let client = clientList[i] -// let clientPath = (new URL(client.url)).pathname -// -// if (clientPath == event.notification.data.path && "focus" in client) { -// return client.focus() -// } -// } -// -// if (clients.openWindow) { -// return clients.openWindow(event.notification.data.path) -// } -// }) -// ) -// }) diff --git a/examples/rails-demo/bin/brakeman b/examples/rails-demo/bin/brakeman deleted file mode 100755 index ace1c9b..0000000 --- a/examples/rails-demo/bin/brakeman +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby -require "rubygems" -require "bundler/setup" - -ARGV.unshift("--ensure-latest") - -load Gem.bin_path("brakeman", "brakeman") diff --git a/examples/rails-demo/bin/bundle b/examples/rails-demo/bin/bundle deleted file mode 100755 index 50da5fd..0000000 --- a/examples/rails-demo/bin/bundle +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# -# This file was generated by Bundler. -# -# The application 'bundle' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require "rubygems" - -m = Module.new do - module_function - - def invoked_as_script? - File.expand_path($0) == File.expand_path(__FILE__) - end - - def env_var_version - ENV["BUNDLER_VERSION"] - end - - def cli_arg_version - return unless invoked_as_script? # don't want to hijack other binstubs - return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` - bundler_version = nil - update_index = nil - ARGV.each_with_index do |a, i| - if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) - bundler_version = a - end - next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ - bundler_version = $1 - update_index = i - end - bundler_version - end - - def gemfile - gemfile = ENV["BUNDLE_GEMFILE"] - return gemfile if gemfile && !gemfile.empty? - - File.expand_path("../Gemfile", __dir__) - end - - def lockfile - lockfile = - case File.basename(gemfile) - when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") - else "#{gemfile}.lock" - end - File.expand_path(lockfile) - end - - def lockfile_version - return unless File.file?(lockfile) - lockfile_contents = File.read(lockfile) - return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ - Regexp.last_match(1) - end - - def bundler_requirement - @bundler_requirement ||= - env_var_version || - cli_arg_version || - bundler_requirement_for(lockfile_version) - end - - def bundler_requirement_for(version) - return "#{Gem::Requirement.default}.a" unless version - - bundler_gem_version = Gem::Version.new(version) - - bundler_gem_version.approximate_recommendation - end - - def load_bundler! - ENV["BUNDLE_GEMFILE"] ||= gemfile - - activate_bundler - end - - def activate_bundler - gem_error = activation_error_handling do - gem "bundler", bundler_requirement - end - return if gem_error.nil? - require_error = activation_error_handling do - require "bundler/version" - end - return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) - warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" - exit 42 - end - - def activation_error_handling - yield - nil - rescue StandardError, LoadError => e - e - end -end - -m.load_bundler! - -if m.invoked_as_script? - load Gem.bin_path("bundler", "bundle") -end diff --git a/examples/rails-demo/bin/dev b/examples/rails-demo/bin/dev deleted file mode 100755 index 5f91c20..0000000 --- a/examples/rails-demo/bin/dev +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env ruby -exec "./bin/rails", "server", *ARGV diff --git a/examples/rails-demo/bin/docker-entrypoint b/examples/rails-demo/bin/docker-entrypoint deleted file mode 100755 index 57567d6..0000000 --- a/examples/rails-demo/bin/docker-entrypoint +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -e - -# Enable jemalloc for reduced memory usage and latency. -if [ -z "${LD_PRELOAD+x}" ]; then - LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit) - export LD_PRELOAD -fi - -# If running the rails server then create or migrate existing database -if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then - ./bin/rails db:prepare -fi - -exec "${@}" diff --git a/examples/rails-demo/bin/importmap b/examples/rails-demo/bin/importmap deleted file mode 100755 index 36502ab..0000000 --- a/examples/rails-demo/bin/importmap +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby - -require_relative "../config/application" -require "importmap/commands" diff --git a/examples/rails-demo/bin/jobs b/examples/rails-demo/bin/jobs deleted file mode 100755 index dcf59f3..0000000 --- a/examples/rails-demo/bin/jobs +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env ruby - -require_relative "../config/environment" -require "solid_queue/cli" - -SolidQueue::Cli.start(ARGV) diff --git a/examples/rails-demo/bin/kamal b/examples/rails-demo/bin/kamal deleted file mode 100755 index cbe59b9..0000000 --- a/examples/rails-demo/bin/kamal +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# -# This file was generated by Bundler. -# -# The application 'kamal' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) - -bundle_binstub = File.expand_path("bundle", __dir__) - -if File.file?(bundle_binstub) - if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") - load(bundle_binstub) - else - abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. -Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") - end -end - -require "rubygems" -require "bundler/setup" - -load Gem.bin_path("kamal", "kamal") diff --git a/examples/rails-demo/bin/rails b/examples/rails-demo/bin/rails deleted file mode 100755 index efc0377..0000000 --- a/examples/rails-demo/bin/rails +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby -APP_PATH = File.expand_path("../config/application", __dir__) -require_relative "../config/boot" -require "rails/commands" diff --git a/examples/rails-demo/bin/rake b/examples/rails-demo/bin/rake deleted file mode 100755 index 4fbf10b..0000000 --- a/examples/rails-demo/bin/rake +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby -require_relative "../config/boot" -require "rake" -Rake.application.run diff --git a/examples/rails-demo/bin/rubocop b/examples/rails-demo/bin/rubocop deleted file mode 100755 index 40330c0..0000000 --- a/examples/rails-demo/bin/rubocop +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env ruby -require "rubygems" -require "bundler/setup" - -# explicit rubocop config increases performance slightly while avoiding config confusion. -ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) - -load Gem.bin_path("rubocop", "rubocop") diff --git a/examples/rails-demo/bin/setup b/examples/rails-demo/bin/setup deleted file mode 100755 index be3db3c..0000000 --- a/examples/rails-demo/bin/setup +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env ruby -require "fileutils" - -APP_ROOT = File.expand_path("..", __dir__) - -def system!(*args) - system(*args, exception: true) -end - -FileUtils.chdir APP_ROOT do - # This script is a way to set up or update your development environment automatically. - # This script is idempotent, so that you can run it at any time and get an expectable outcome. - # Add necessary setup steps to this file. - - puts "== Installing dependencies ==" - system("bundle check") || system!("bundle install") - - # puts "\n== Copying sample files ==" - # unless File.exist?("config/database.yml") - # FileUtils.cp "config/database.yml.sample", "config/database.yml" - # end - - puts "\n== Preparing database ==" - system! "bin/rails db:prepare" - - puts "\n== Removing old logs and tempfiles ==" - system! "bin/rails log:clear tmp:clear" - - unless ARGV.include?("--skip-server") - puts "\n== Starting development server ==" - STDOUT.flush # flush the output before exec(2) so that it displays - exec "bin/dev" - end -end diff --git a/examples/rails-demo/bin/thrust b/examples/rails-demo/bin/thrust deleted file mode 100755 index 36bde2d..0000000 --- a/examples/rails-demo/bin/thrust +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env ruby -require "rubygems" -require "bundler/setup" - -load Gem.bin_path("thruster", "thrust") diff --git a/examples/rails-demo/config.ru b/examples/rails-demo/config.ru deleted file mode 100644 index 4a3c09a..0000000 --- a/examples/rails-demo/config.ru +++ /dev/null @@ -1,6 +0,0 @@ -# This file is used by Rack-based servers to start the application. - -require_relative "config/environment" - -run Rails.application -Rails.application.load_server diff --git a/examples/rails-demo/config/application.rb b/examples/rails-demo/config/application.rb deleted file mode 100644 index 13a469a..0000000 --- a/examples/rails-demo/config/application.rb +++ /dev/null @@ -1,27 +0,0 @@ -require_relative "boot" - -require "rails/all" - -# Require the gems listed in Gemfile, including any gems -# you've limited to :test, :development, or :production. -Bundler.require(*Rails.groups) - -module AppDemo - class Application < Rails::Application - # Initialize configuration defaults for originally generated Rails version. - config.load_defaults 8.0 - - # Please, add to the `ignore` list any other `lib` subdirectories that do - # not contain `.rb` files, or that should not be reloaded or eager loaded. - # Common ones are `templates`, `generators`, or `middleware`, for example. - config.autoload_lib(ignore: %w[assets tasks]) - - # Configuration for the application, engines, and railties goes here. - # - # These settings can be overridden in specific environments using the files - # in config/environments, which are processed later. - # - # config.time_zone = "Central Time (US & Canada)" - # config.eager_load_paths << Rails.root.join("extras") - end -end diff --git a/examples/rails-demo/config/boot.rb b/examples/rails-demo/config/boot.rb deleted file mode 100644 index 988a5dd..0000000 --- a/examples/rails-demo/config/boot.rb +++ /dev/null @@ -1,4 +0,0 @@ -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) - -require "bundler/setup" # Set up gems listed in the Gemfile. -require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/examples/rails-demo/config/cable.yml b/examples/rails-demo/config/cable.yml deleted file mode 100644 index b9adc5a..0000000 --- a/examples/rails-demo/config/cable.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Async adapter only works within the same process, so for manually triggering cable updates from a console, -# and seeing results in the browser, you must do so from the web console (running inside the dev process), -# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view -# to make the web console appear. -development: - adapter: async - -test: - adapter: test - -production: - adapter: solid_cable - connects_to: - database: - writing: cable - polling_interval: 0.1.seconds - message_retention: 1.day diff --git a/examples/rails-demo/config/cache.yml b/examples/rails-demo/config/cache.yml deleted file mode 100644 index 19d4908..0000000 --- a/examples/rails-demo/config/cache.yml +++ /dev/null @@ -1,16 +0,0 @@ -default: &default - store_options: - # Cap age of oldest cache entry to fulfill retention policies - # max_age: <%= 60.days.to_i %> - max_size: <%= 256.megabytes %> - namespace: <%= Rails.env %> - -development: - <<: *default - -test: - <<: *default - -production: - database: cache - <<: *default diff --git a/examples/rails-demo/config/credentials.yml.enc b/examples/rails-demo/config/credentials.yml.enc deleted file mode 100644 index f41db04..0000000 --- a/examples/rails-demo/config/credentials.yml.enc +++ /dev/null @@ -1 +0,0 @@ -WYIIUJVh9ImHFkXx8GZZqIHJjgLNLkZ4ilM9wFA2J7Pw6F9uAZ8iCGvPn4rL1ThXzdZLWQutIPD608JJTsBFZoJsPUsI3F2dXGE7D3kvXsM6EGc2e2F4u7npPwd94dHPoL398DCNiL9yYy2wWEW4U35NSRilK9eguLqmasttFBk8nfpoXt4A2D26pSU1vKyft+7/ZFDMduSMvE+stQM1SWdvdSZIDcMMajw5LWIjslhakn3QA1iO87qJtzCm2mWRgEiVyZWeIBovZ9akW1apsq0F67QnC1+6p/zh0ZTbalhe+ENkJO49arMFf8C9pZm5inFZrwO6vmviMaWspbTt6hcou4agiC3nBCqF3fHvmpKgQsXLyRHYNkoMPmuHVjilv9nW8O/vnRBuFXJN8MRS2fzGGTC1G2Pija2TTFmb7KzdF3rkhXQHQlUm0LQXlx8l/RgYdQeHQ8lhpaVge0jZJ0Aquyb396jc+gIlZiaHTNffQ6r6/cEa1Gj+--HhZpI/RF7QrOmZNy--/vy5cF/99DGDY67RSRzvQA== \ No newline at end of file diff --git a/examples/rails-demo/config/database.yml b/examples/rails-demo/config/database.yml deleted file mode 100644 index 2640cb5..0000000 --- a/examples/rails-demo/config/database.yml +++ /dev/null @@ -1,41 +0,0 @@ -# SQLite. Versions 3.8.0 and up are supported. -# gem install sqlite3 -# -# Ensure the SQLite 3 gem is defined in your Gemfile -# gem "sqlite3" -# -default: &default - adapter: sqlite3 - pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - timeout: 5000 - -development: - <<: *default - database: storage/development.sqlite3 - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: storage/test.sqlite3 - - -# Store production database in the storage/ directory, which by default -# is mounted as a persistent Docker volume in config/deploy.yml. -production: - primary: - <<: *default - database: storage/production.sqlite3 - cache: - <<: *default - database: storage/production_cache.sqlite3 - migrations_paths: db/cache_migrate - queue: - <<: *default - database: storage/production_queue.sqlite3 - migrations_paths: db/queue_migrate - cable: - <<: *default - database: storage/production_cable.sqlite3 - migrations_paths: db/cable_migrate diff --git a/examples/rails-demo/config/deploy.yml b/examples/rails-demo/config/deploy.yml deleted file mode 100644 index 0cb852d..0000000 --- a/examples/rails-demo/config/deploy.yml +++ /dev/null @@ -1,116 +0,0 @@ -# Name of your application. Used to uniquely configure containers. -service: app_demo - -# Name of the container image. -image: your-user/app_demo - -# Deploy to these servers. -servers: - web: - - 192.168.0.1 - # job: - # hosts: - # - 192.168.0.1 - # cmd: bin/jobs - -# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. -# Remove this section when using multiple web servers and ensure you terminate SSL at your load balancer. -# -# Note: If using Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. -proxy: - ssl: true - host: app.example.com - -# Credentials for your image host. -registry: - # Specify the registry server, if you're not using Docker Hub - # server: registry.digitalocean.com / ghcr.io / ... - username: your-user - - # Always use an access token rather than real password when possible. - password: - - KAMAL_REGISTRY_PASSWORD - -# Inject ENV variables into containers (secrets come from .kamal/secrets). -env: - secret: - - RAILS_MASTER_KEY - clear: - # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. - # When you start using multiple servers, you should split out job processing to a dedicated machine. - SOLID_QUEUE_IN_PUMA: true - - # Set number of processes dedicated to Solid Queue (default: 1) - # JOB_CONCURRENCY: 3 - - # Set number of cores available to the application on each server (default: 1). - # WEB_CONCURRENCY: 2 - - # Match this to any external database server to configure Active Record correctly - # Use app_demo-db for a db accessory server on same machine via local kamal docker network. - # DB_HOST: 192.168.0.2 - - # Log everything from Rails - # RAILS_LOG_LEVEL: debug - -# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: -# "bin/kamal logs -r job" will tail logs from the first server in the job section. -aliases: - console: app exec --interactive --reuse "bin/rails console" - shell: app exec --interactive --reuse "bash" - logs: app logs -f - dbc: app exec --interactive --reuse "bin/rails dbconsole" - - -# Use a persistent storage volume for sqlite database files and local Active Storage files. -# Recommended to change this to a mounted volume path that is backed up off server. -volumes: - - "app_demo_storage:/rails/storage" - - -# Bridge fingerprinted assets, like JS and CSS, between versions to avoid -# hitting 404 on in-flight requests. Combines all files from new and old -# version inside the asset_path. -asset_path: /rails/public/assets - -# Configure the image builder. -builder: - arch: amd64 - - # # Build image via remote server (useful for faster amd64 builds on arm64 computers) - # remote: ssh://docker@docker-builder-server - # - # # Pass arguments and secrets to the Docker build process - # args: - # RUBY_VERSION: ruby-3.2.2 - # secrets: - # - GITHUB_TOKEN - # - RAILS_MASTER_KEY - -# Use a different ssh user than root -# ssh: -# user: app - -# Use accessory services (secrets come from .kamal/secrets). -# accessories: -# db: -# image: mysql:8.0 -# host: 192.168.0.2 -# # Change to 3306 to expose port to the world instead of just local network. -# port: "127.0.0.1:3306:3306" -# env: -# clear: -# MYSQL_ROOT_HOST: '%' -# secret: -# - MYSQL_ROOT_PASSWORD -# files: -# - config/mysql/production.cnf:/etc/mysql/my.cnf -# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql -# directories: -# - data:/var/lib/mysql -# redis: -# image: redis:7.0 -# host: 192.168.0.2 -# port: 6379 -# directories: -# - data:/data diff --git a/examples/rails-demo/config/environment.rb b/examples/rails-demo/config/environment.rb deleted file mode 100644 index cac5315..0000000 --- a/examples/rails-demo/config/environment.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Load the Rails application. -require_relative "application" - -# Initialize the Rails application. -Rails.application.initialize! diff --git a/examples/rails-demo/config/environments/development.rb b/examples/rails-demo/config/environments/development.rb deleted file mode 100644 index 4cc21c4..0000000 --- a/examples/rails-demo/config/environments/development.rb +++ /dev/null @@ -1,72 +0,0 @@ -require "active_support/core_ext/integer/time" - -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # Make code changes take effect immediately without server restart. - config.enable_reloading = true - - # Do not eager load code on boot. - config.eager_load = false - - # Show full error reports. - config.consider_all_requests_local = true - - # Enable server timing. - config.server_timing = true - - # Enable/disable Action Controller caching. By default Action Controller caching is disabled. - # Run rails dev:cache to toggle Action Controller caching. - if Rails.root.join("tmp/caching-dev.txt").exist? - config.action_controller.perform_caching = true - config.action_controller.enable_fragment_cache_logging = true - config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } - else - config.action_controller.perform_caching = false - end - - # Change to :null_store to avoid any caching. - config.cache_store = :memory_store - - # Store uploaded files on the local file system (see config/storage.yml for options). - config.active_storage.service = :local - - # Don't care if the mailer can't send. - config.action_mailer.raise_delivery_errors = false - - # Make template changes take effect immediately. - config.action_mailer.perform_caching = false - - # Set localhost to be used by links generated in mailer templates. - config.action_mailer.default_url_options = { host: "localhost", port: 3000 } - - # Print deprecation notices to the Rails logger. - config.active_support.deprecation = :log - - # Raise an error on page load if there are pending migrations. - config.active_record.migration_error = :page_load - - # Highlight code that triggered database queries in logs. - config.active_record.verbose_query_logs = true - - # Append comments with runtime information tags to SQL queries in logs. - config.active_record.query_log_tags_enabled = true - - # Highlight code that enqueued background job in logs. - config.active_job.verbose_enqueue_logs = true - - # Raises error for missing translations. - # config.i18n.raise_on_missing_translations = true - - # Annotate rendered view with file names. - config.action_view.annotate_rendered_view_with_filenames = true - - # Uncomment if you wish to allow Action Cable access from any origin. - # config.action_cable.disable_request_forgery_protection = true - - # Raise error when a before_action's only/except options reference missing actions. - config.action_controller.raise_on_missing_callback_actions = true - - # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. - # config.generators.apply_rubocop_autocorrect_after_generate! -end diff --git a/examples/rails-demo/config/environments/production.rb b/examples/rails-demo/config/environments/production.rb deleted file mode 100644 index bdcd01d..0000000 --- a/examples/rails-demo/config/environments/production.rb +++ /dev/null @@ -1,90 +0,0 @@ -require "active_support/core_ext/integer/time" - -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # Code is not reloaded between requests. - config.enable_reloading = false - - # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). - config.eager_load = true - - # Full error reports are disabled. - config.consider_all_requests_local = false - - # Turn on fragment caching in view templates. - config.action_controller.perform_caching = true - - # Cache assets for far-future expiry since they are all digest stamped. - config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } - - # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.asset_host = "http://assets.example.com" - - # Store uploaded files on the local file system (see config/storage.yml for options). - config.active_storage.service = :local - - # Assume all access to the app is happening through a SSL-terminating reverse proxy. - config.assume_ssl = true - - # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. - config.force_ssl = true - - # Skip http-to-https redirect for the default health check endpoint. - # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } - - # Log to STDOUT with the current request id as a default log tag. - config.log_tags = [ :request_id ] - config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) - - # Change to "debug" to log everything (including potentially personally-identifiable information!) - config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") - - # Prevent health checks from clogging up the logs. - config.silence_healthcheck_path = "/up" - - # Don't log any deprecations. - config.active_support.report_deprecations = false - - # Replace the default in-process memory cache store with a durable alternative. - config.cache_store = :solid_cache_store - - # Replace the default in-process and non-durable queuing backend for Active Job. - config.active_job.queue_adapter = :solid_queue - config.solid_queue.connects_to = { database: { writing: :queue } } - - # Ignore bad email addresses and do not raise email delivery errors. - # Set this to true and configure the email server for immediate delivery to raise delivery errors. - # config.action_mailer.raise_delivery_errors = false - - # Set host to be used by links generated in mailer templates. - config.action_mailer.default_url_options = { host: "example.com" } - - # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. - # config.action_mailer.smtp_settings = { - # user_name: Rails.application.credentials.dig(:smtp, :user_name), - # password: Rails.application.credentials.dig(:smtp, :password), - # address: "smtp.example.com", - # port: 587, - # authentication: :plain - # } - - # Enable locale fallbacks for I18n (makes lookups for any locale fall back to - # the I18n.default_locale when a translation cannot be found). - config.i18n.fallbacks = true - - # Do not dump schema after migrations. - config.active_record.dump_schema_after_migration = false - - # Only use :id for inspections in production. - config.active_record.attributes_for_inspect = [ :id ] - - # Enable DNS rebinding protection and other `Host` header attacks. - # config.hosts = [ - # "example.com", # Allow requests from example.com - # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` - # ] - # - # Skip DNS rebinding protection for the default health check endpoint. - # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } -end diff --git a/examples/rails-demo/config/environments/test.rb b/examples/rails-demo/config/environments/test.rb deleted file mode 100644 index c2095b1..0000000 --- a/examples/rails-demo/config/environments/test.rb +++ /dev/null @@ -1,53 +0,0 @@ -# The test environment is used exclusively to run your application's -# test suite. You never need to work with it otherwise. Remember that -# your test database is "scratch space" for the test suite and is wiped -# and recreated between test runs. Don't rely on the data there! - -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # While tests run files are not watched, reloading is not necessary. - config.enable_reloading = false - - # Eager loading loads your entire application. When running a single test locally, - # this is usually not necessary, and can slow down your test suite. However, it's - # recommended that you enable it in continuous integration systems to ensure eager - # loading is working properly before deploying your code. - config.eager_load = ENV["CI"].present? - - # Configure public file server for tests with cache-control for performance. - config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } - - # Show full error reports. - config.consider_all_requests_local = true - config.cache_store = :null_store - - # Render exception templates for rescuable exceptions and raise for other exceptions. - config.action_dispatch.show_exceptions = :rescuable - - # Disable request forgery protection in test environment. - config.action_controller.allow_forgery_protection = false - - # Store uploaded files on the local file system in a temporary directory. - config.active_storage.service = :test - - # Tell Action Mailer not to deliver emails to the real world. - # The :test delivery method accumulates sent emails in the - # ActionMailer::Base.deliveries array. - config.action_mailer.delivery_method = :test - - # Set host to be used by links generated in mailer templates. - config.action_mailer.default_url_options = { host: "example.com" } - - # Print deprecation notices to the stderr. - config.active_support.deprecation = :stderr - - # Raises error for missing translations. - # config.i18n.raise_on_missing_translations = true - - # Annotate rendered view with file names. - # config.action_view.annotate_rendered_view_with_filenames = true - - # Raise error when a before_action's only/except options reference missing actions. - config.action_controller.raise_on_missing_callback_actions = true -end diff --git a/examples/rails-demo/config/importmap.rb b/examples/rails-demo/config/importmap.rb deleted file mode 100644 index 909dfc5..0000000 --- a/examples/rails-demo/config/importmap.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Pin npm packages by running ./bin/importmap - -pin "application" -pin "@hotwired/turbo-rails", to: "turbo.min.js" -pin "@hotwired/stimulus", to: "stimulus.min.js" -pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" -pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/examples/rails-demo/config/initializers/assets.rb b/examples/rails-demo/config/initializers/assets.rb deleted file mode 100644 index 4873244..0000000 --- a/examples/rails-demo/config/initializers/assets.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = "1.0" - -# Add additional assets to the asset load path. -# Rails.application.config.assets.paths << Emoji.images_path diff --git a/examples/rails-demo/config/initializers/content_security_policy.rb b/examples/rails-demo/config/initializers/content_security_policy.rb deleted file mode 100644 index b3076b3..0000000 --- a/examples/rails-demo/config/initializers/content_security_policy.rb +++ /dev/null @@ -1,25 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Define an application-wide content security policy. -# See the Securing Rails Applications Guide for more information: -# https://guides.rubyonrails.org/security.html#content-security-policy-header - -# Rails.application.configure do -# config.content_security_policy do |policy| -# policy.default_src :self, :https -# policy.font_src :self, :https, :data -# policy.img_src :self, :https, :data -# policy.object_src :none -# policy.script_src :self, :https -# policy.style_src :self, :https -# # Specify URI for violation reports -# # policy.report_uri "/csp-violation-report-endpoint" -# end -# -# # Generate session nonces for permitted importmap, inline scripts, and inline styles. -# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } -# config.content_security_policy_nonce_directives = %w(script-src style-src) -# -# # Report violations without enforcing the policy. -# # config.content_security_policy_report_only = true -# end diff --git a/examples/rails-demo/config/initializers/filter_parameter_logging.rb b/examples/rails-demo/config/initializers/filter_parameter_logging.rb deleted file mode 100644 index c0b717f..0000000 --- a/examples/rails-demo/config/initializers/filter_parameter_logging.rb +++ /dev/null @@ -1,8 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. -# Use this to limit dissemination of sensitive information. -# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. -Rails.application.config.filter_parameters += [ - :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc -] diff --git a/examples/rails-demo/config/initializers/inflections.rb b/examples/rails-demo/config/initializers/inflections.rb deleted file mode 100644 index 3860f65..0000000 --- a/examples/rails-demo/config/initializers/inflections.rb +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Add new inflection rules using the following format. Inflections -# are locale specific, and you may define rules for as many different -# locales as you wish. All of these examples are active by default: -# ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.plural /^(ox)$/i, "\\1en" -# inflect.singular /^(ox)en/i, "\\1" -# inflect.irregular "person", "people" -# inflect.uncountable %w( fish sheep ) -# end - -# These inflection rules are supported but not enabled by default: -# ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.acronym "RESTful" -# end diff --git a/examples/rails-demo/config/locales/en.yml b/examples/rails-demo/config/locales/en.yml deleted file mode 100644 index 6c349ae..0000000 --- a/examples/rails-demo/config/locales/en.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Files in the config/locales directory are used for internationalization and -# are automatically loaded by Rails. If you want to use locales other than -# English, add the necessary files in this directory. -# -# To use the locales, use `I18n.t`: -# -# I18n.t "hello" -# -# In views, this is aliased to just `t`: -# -# <%= t("hello") %> -# -# To use a different locale, set it with `I18n.locale`: -# -# I18n.locale = :es -# -# This would use the information in config/locales/es.yml. -# -# To learn more about the API, please read the Rails Internationalization guide -# at https://guides.rubyonrails.org/i18n.html. -# -# Be aware that YAML interprets the following case-insensitive strings as -# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings -# must be quoted to be interpreted as strings. For example: -# -# en: -# "yes": yup -# enabled: "ON" - -en: - hello: "Hello world" diff --git a/examples/rails-demo/config/puma.rb b/examples/rails-demo/config/puma.rb deleted file mode 100644 index a248513..0000000 --- a/examples/rails-demo/config/puma.rb +++ /dev/null @@ -1,41 +0,0 @@ -# This configuration file will be evaluated by Puma. The top-level methods that -# are invoked here are part of Puma's configuration DSL. For more information -# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. -# -# Puma starts a configurable number of processes (workers) and each process -# serves each request in a thread from an internal thread pool. -# -# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You -# should only set this value when you want to run 2 or more workers. The -# default is already 1. -# -# The ideal number of threads per worker depends both on how much time the -# application spends waiting for IO operations and on how much you wish to -# prioritize throughput over latency. -# -# As a rule of thumb, increasing the number of threads will increase how much -# traffic a given process can handle (throughput), but due to CRuby's -# Global VM Lock (GVL) it has diminishing returns and will degrade the -# response time (latency) of the application. -# -# The default is set to 3 threads as it's deemed a decent compromise between -# throughput and latency for the average Rails application. -# -# Any libraries that use a connection pool or another resource pool should -# be configured to provide at least as many connections as the number of -# threads. This includes Active Record's `pool` parameter in `database.yml`. -threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) -threads threads_count, threads_count - -# Specifies the `port` that Puma will listen on to receive requests; default is 3000. -port ENV.fetch("PORT", 3000) - -# Allow puma to be restarted by `bin/rails restart` command. -plugin :tmp_restart - -# Run the Solid Queue supervisor inside of Puma for single-server deployments -plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"] - -# Specify the PID file. Defaults to tmp/pids/server.pid in development. -# In other environments, only set the PID file if requested. -pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/examples/rails-demo/config/queue.yml b/examples/rails-demo/config/queue.yml deleted file mode 100644 index 9eace59..0000000 --- a/examples/rails-demo/config/queue.yml +++ /dev/null @@ -1,18 +0,0 @@ -default: &default - dispatchers: - - polling_interval: 1 - batch_size: 500 - workers: - - queues: "*" - threads: 3 - processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> - polling_interval: 0.1 - -development: - <<: *default - -test: - <<: *default - -production: - <<: *default diff --git a/examples/rails-demo/config/recurring.yml b/examples/rails-demo/config/recurring.yml deleted file mode 100644 index d045b19..0000000 --- a/examples/rails-demo/config/recurring.yml +++ /dev/null @@ -1,10 +0,0 @@ -# production: -# periodic_cleanup: -# class: CleanSoftDeletedRecordsJob -# queue: background -# args: [ 1000, { batch_size: 500 } ] -# schedule: every hour -# periodic_command: -# command: "SoftDeletedRecord.due.delete_all" -# priority: 2 -# schedule: at 5am every day diff --git a/examples/rails-demo/config/routes.rb b/examples/rails-demo/config/routes.rb deleted file mode 100644 index 48254e8..0000000 --- a/examples/rails-demo/config/routes.rb +++ /dev/null @@ -1,14 +0,0 @@ -Rails.application.routes.draw do - # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html - - # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. - # Can be used by load balancers and uptime monitors to verify that the app is live. - get "up" => "rails/health#show", as: :rails_health_check - - # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) - # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest - # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker - - # Defines the root path route ("/") - # root "posts#index" -end diff --git a/examples/rails-demo/config/storage.yml b/examples/rails-demo/config/storage.yml deleted file mode 100644 index 4942ab6..0000000 --- a/examples/rails-demo/config/storage.yml +++ /dev/null @@ -1,34 +0,0 @@ -test: - service: Disk - root: <%= Rails.root.join("tmp/storage") %> - -local: - service: Disk - root: <%= Rails.root.join("storage") %> - -# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) -# amazon: -# service: S3 -# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> -# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> -# region: us-east-1 -# bucket: your_own_bucket-<%= Rails.env %> - -# Remember not to checkin your GCS keyfile to a repository -# google: -# service: GCS -# project: your_project -# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> -# bucket: your_own_bucket-<%= Rails.env %> - -# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) -# microsoft: -# service: AzureStorage -# storage_account_name: your_account_name -# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> -# container: your_container_name-<%= Rails.env %> - -# mirror: -# service: Mirror -# primary: local -# mirrors: [ amazon, google, microsoft ] diff --git a/examples/rails-demo/db/cable_schema.rb b/examples/rails-demo/db/cable_schema.rb deleted file mode 100644 index 2366660..0000000 --- a/examples/rails-demo/db/cable_schema.rb +++ /dev/null @@ -1,11 +0,0 @@ -ActiveRecord::Schema[7.1].define(version: 1) do - create_table "solid_cable_messages", force: :cascade do |t| - t.binary "channel", limit: 1024, null: false - t.binary "payload", limit: 536870912, null: false - t.datetime "created_at", null: false - t.integer "channel_hash", limit: 8, null: false - t.index ["channel"], name: "index_solid_cable_messages_on_channel" - t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash" - t.index ["created_at"], name: "index_solid_cable_messages_on_created_at" - end -end diff --git a/examples/rails-demo/db/cache_schema.rb b/examples/rails-demo/db/cache_schema.rb deleted file mode 100644 index 6005a29..0000000 --- a/examples/rails-demo/db/cache_schema.rb +++ /dev/null @@ -1,14 +0,0 @@ -# frozen_string_literal: true - -ActiveRecord::Schema[7.2].define(version: 1) do - create_table "solid_cache_entries", force: :cascade do |t| - t.binary "key", limit: 1024, null: false - t.binary "value", limit: 536870912, null: false - t.datetime "created_at", null: false - t.integer "key_hash", limit: 8, null: false - t.integer "byte_size", limit: 4, null: false - t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size" - t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size" - t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true - end -end diff --git a/examples/rails-demo/db/queue_schema.rb b/examples/rails-demo/db/queue_schema.rb deleted file mode 100644 index 85194b6..0000000 --- a/examples/rails-demo/db/queue_schema.rb +++ /dev/null @@ -1,129 +0,0 @@ -ActiveRecord::Schema[7.1].define(version: 1) do - create_table "solid_queue_blocked_executions", force: :cascade do |t| - t.bigint "job_id", null: false - t.string "queue_name", null: false - t.integer "priority", default: 0, null: false - t.string "concurrency_key", null: false - t.datetime "expires_at", null: false - t.datetime "created_at", null: false - t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" - t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" - t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true - end - - create_table "solid_queue_claimed_executions", force: :cascade do |t| - t.bigint "job_id", null: false - t.bigint "process_id" - t.datetime "created_at", null: false - t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true - t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" - end - - create_table "solid_queue_failed_executions", force: :cascade do |t| - t.bigint "job_id", null: false - t.text "error" - t.datetime "created_at", null: false - t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true - end - - create_table "solid_queue_jobs", force: :cascade do |t| - t.string "queue_name", null: false - t.string "class_name", null: false - t.text "arguments" - t.integer "priority", default: 0, null: false - t.string "active_job_id" - t.datetime "scheduled_at" - t.datetime "finished_at" - t.string "concurrency_key" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" - t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" - t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" - t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" - t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" - end - - create_table "solid_queue_pauses", force: :cascade do |t| - t.string "queue_name", null: false - t.datetime "created_at", null: false - t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true - end - - create_table "solid_queue_processes", force: :cascade do |t| - t.string "kind", null: false - t.datetime "last_heartbeat_at", null: false - t.bigint "supervisor_id" - t.integer "pid", null: false - t.string "hostname" - t.text "metadata" - t.datetime "created_at", null: false - t.string "name", null: false - t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" - t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true - t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" - end - - create_table "solid_queue_ready_executions", force: :cascade do |t| - t.bigint "job_id", null: false - t.string "queue_name", null: false - t.integer "priority", default: 0, null: false - t.datetime "created_at", null: false - t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true - t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" - t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" - end - - create_table "solid_queue_recurring_executions", force: :cascade do |t| - t.bigint "job_id", null: false - t.string "task_key", null: false - t.datetime "run_at", null: false - t.datetime "created_at", null: false - t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true - t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true - end - - create_table "solid_queue_recurring_tasks", force: :cascade do |t| - t.string "key", null: false - t.string "schedule", null: false - t.string "command", limit: 2048 - t.string "class_name" - t.text "arguments" - t.string "queue_name" - t.integer "priority", default: 0 - t.boolean "static", default: true, null: false - t.text "description" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true - t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" - end - - create_table "solid_queue_scheduled_executions", force: :cascade do |t| - t.bigint "job_id", null: false - t.string "queue_name", null: false - t.integer "priority", default: 0, null: false - t.datetime "scheduled_at", null: false - t.datetime "created_at", null: false - t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true - t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" - end - - create_table "solid_queue_semaphores", force: :cascade do |t| - t.string "key", null: false - t.integer "value", default: 1, null: false - t.datetime "expires_at", null: false - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" - t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" - t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true - end - - add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade - add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade - add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade - add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade - add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade - add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade -end diff --git a/examples/rails-demo/db/seeds.rb b/examples/rails-demo/db/seeds.rb deleted file mode 100644 index 4fbd6ed..0000000 --- a/examples/rails-demo/db/seeds.rb +++ /dev/null @@ -1,9 +0,0 @@ -# This file should ensure the existence of records required to run the application in every environment (production, -# development, test). The code here should be idempotent so that it can be executed at any point in every environment. -# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). -# -# Example: -# -# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| -# MovieGenre.find_or_create_by!(name: genre_name) -# end diff --git a/examples/rails-demo/lib/tasks/.keep b/examples/rails-demo/lib/tasks/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/log/.keep b/examples/rails-demo/log/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/public/400.html b/examples/rails-demo/public/400.html deleted file mode 100644 index 282dbc8..0000000 --- a/examples/rails-demo/public/400.html +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - The server cannot process the request due to a client error (400 Bad Request) - - - - - - - - - - - - - -
-
- -
-
-

The server cannot process the request due to a client error. Please check the request and try again. If you’re the application owner check the logs for more information.

-
-
- - - - diff --git a/examples/rails-demo/public/404.html b/examples/rails-demo/public/404.html deleted file mode 100644 index c0670bc..0000000 --- a/examples/rails-demo/public/404.html +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - The page you were looking for doesn’t exist (404 Not found) - - - - - - - - - - - - - -
-
- -
-
-

The page you were looking for doesn’t exist. You may have mistyped the address or the page may have moved. If you’re the application owner check the logs for more information.

-
-
- - - - diff --git a/examples/rails-demo/public/406-unsupported-browser.html b/examples/rails-demo/public/406-unsupported-browser.html deleted file mode 100644 index 9532a9c..0000000 --- a/examples/rails-demo/public/406-unsupported-browser.html +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - Your browser is not supported (406 Not Acceptable) - - - - - - - - - - - - - -
-
- -
-
-

Your browser is not supported.
Please upgrade your browser to continue.

-
-
- - - - diff --git a/examples/rails-demo/public/422.html b/examples/rails-demo/public/422.html deleted file mode 100644 index 8bcf060..0000000 --- a/examples/rails-demo/public/422.html +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - The change you wanted was rejected (422 Unprocessable Entity) - - - - - - - - - - - - - -
-
- -
-
-

The change you wanted was rejected. Maybe you tried to change something you didn’t have access to. If you’re the application owner check the logs for more information.

-
-
- - - - diff --git a/examples/rails-demo/public/500.html b/examples/rails-demo/public/500.html deleted file mode 100644 index d77718c..0000000 --- a/examples/rails-demo/public/500.html +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - We’re sorry, but something went wrong (500 Internal Server Error) - - - - - - - - - - - - - -
-
- -
-
-

We’re sorry, but something went wrong.
If you’re the application owner check the logs for more information.

-
-
- - - - diff --git a/examples/rails-demo/public/icon.png b/examples/rails-demo/public/icon.png deleted file mode 100644 index c4c9dbf..0000000 Binary files a/examples/rails-demo/public/icon.png and /dev/null differ diff --git a/examples/rails-demo/public/icon.svg b/examples/rails-demo/public/icon.svg deleted file mode 100644 index 04b34bf..0000000 --- a/examples/rails-demo/public/icon.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/examples/rails-demo/public/robots.txt b/examples/rails-demo/public/robots.txt deleted file mode 100644 index c19f78a..0000000 --- a/examples/rails-demo/public/robots.txt +++ /dev/null @@ -1 +0,0 @@ -# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/examples/rails-demo/script/.keep b/examples/rails-demo/script/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/storage/.keep b/examples/rails-demo/storage/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/application_system_test_case.rb b/examples/rails-demo/test/application_system_test_case.rb deleted file mode 100644 index cee29fd..0000000 --- a/examples/rails-demo/test/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] -end diff --git a/examples/rails-demo/test/controllers/.keep b/examples/rails-demo/test/controllers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/fixtures/files/.keep b/examples/rails-demo/test/fixtures/files/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/helpers/.keep b/examples/rails-demo/test/helpers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/integration/.keep b/examples/rails-demo/test/integration/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/mailers/.keep b/examples/rails-demo/test/mailers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/models/.keep b/examples/rails-demo/test/models/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/system/.keep b/examples/rails-demo/test/system/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/test/test_helper.rb b/examples/rails-demo/test/test_helper.rb deleted file mode 100644 index 0c22470..0000000 --- a/examples/rails-demo/test/test_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ -ENV["RAILS_ENV"] ||= "test" -require_relative "../config/environment" -require "rails/test_help" - -module ActiveSupport - class TestCase - # Run tests in parallel with specified workers - parallelize(workers: :number_of_processors) - - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - fixtures :all - - # Add more helper methods to be used by all tests here... - end -end diff --git a/examples/rails-demo/tmp/.keep b/examples/rails-demo/tmp/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/tmp/pids/.keep b/examples/rails-demo/tmp/pids/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/tmp/storage/.keep b/examples/rails-demo/tmp/storage/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/vendor/.keep b/examples/rails-demo/vendor/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/rails-demo/vendor/javascript/.keep b/examples/rails-demo/vendor/javascript/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/examples/sinatra-demo/sinatra-demo.rb b/examples/sinatra-demo/sinatra-demo.rb index 4512dd2..9b8720c 100644 --- a/examples/sinatra-demo/sinatra-demo.rb +++ b/examples/sinatra-demo/sinatra-demo.rb @@ -15,8 +15,8 @@ require 'sinatra' require 'redis' +require 'skywalking' -require_relative '../../lib/skywalking' Skywalking.start get '/sw' do @@ -27,6 +27,5 @@ redis = Redis.new(host: 'localhost', port: 6379) redis.set('hello', 'world') value = redis.get("hello") - puts "Value of 'hello': #{value}" - "Hello #{params[:name]}!" + "Hello #{value}!" end \ No newline at end of file diff --git a/lib/skywalking/configuration.rb b/lib/skywalking/configuration.rb index 6045b07..43c6d26 100644 --- a/lib/skywalking/configuration.rb +++ b/lib/skywalking/configuration.rb @@ -29,7 +29,7 @@ class Configuration default: 'Your_InstanceName', desc: 'The name of this particular awesome Ruby service instance' }, - :collector_backend_service => { + :collector_backend_services => { type: :string, default: '127.0.0.1:11800', desc: 'Backend service addresses' diff --git a/lib/skywalking/plugins/net_http.rb b/lib/skywalking/plugins/net_http.rb new file mode 100644 index 0000000..64cb328 --- /dev/null +++ b/lib/skywalking/plugins/net_http.rb @@ -0,0 +1,73 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +module Skywalking + module Plugins + class NetHttp < PluginsManager::SWPlugin + module HttpIntercept + def request(req, body = nil, &block) + method = req.method + host = req['host']&.split(':')&.first || address || 'localhost' + req_path = URI(req.path) + req_info = "" + uri = if req_path.host + req_path + else + path, query = req.path.split('?') + scheme = use_ssl? ? 'https' : 'http' + req_info = "#{path}#{query ? "?#{query}" : ''}" + full_url = "#{scheme}://#{host}#{":#{port}" if port}#{req_info}" + URI(full_url) + end + + Tracing::ContextManager.new_exit_span( + operation: "#{method}:#{req_info}", + peer: host, + component: Tracing::Component::Http + ) do |span| + span&.tag(Tracing::TagHttpMethod.new(method)) + span&.tag(Tracing::TagHttpURL.new(uri)) + span&.layer = Tracing::Layer::Http + + carrier = span&.inject + headers = req.instance_variable_get(:@header) + carrier&.each do |item| + headers[item.key] ||= [] + headers[item.key].concat(Array(item.value)) + end + + result = super(req, body, &block) + span&.tag(Tracing::TagHttpStatusCode.new(result.code)) + if result.code >= "400" + span&.error_occurred = true + end + + result + end + end + end + + def plugin_valid? + defined?(::Net) && defined?(::Net::HTTP) + end + + def install + ::Net::HTTP.prepend HttpIntercept + end + + register :net_http + end + end +end diff --git a/lib/skywalking/plugins/redis5.rb b/lib/skywalking/plugins/redis5.rb index 8c630dd..db5b777 100644 --- a/lib/skywalking/plugins/redis5.rb +++ b/lib/skywalking/plugins/redis5.rb @@ -26,8 +26,9 @@ def call_v(args, &block) peer: _endpoint_info, component: Tracing::Component::Redis ) do |span| - span&.tag(Tracing::TagDbType.new("Redis")) - span&.layer = Tracing.find_mapping(Tracing::Layer, Tracing::Layer::Cache) + span&.tag(Tracing::TagCacheType.new("Redis")) + span&.tag(Tracing::TagCacheOp.new(operation)) + span&.layer = Tracing::Layer::Cache super(args, &block) end diff --git a/lib/skywalking/plugins/sinatra.rb b/lib/skywalking/plugins/sinatra.rb index ae56513..a9bf511 100644 --- a/lib/skywalking/plugins/sinatra.rb +++ b/lib/skywalking/plugins/sinatra.rb @@ -25,13 +25,13 @@ def dispatch!(*args, &block) end Tracing::ContextManager.new_entry_span( - operation: request.env['REQUEST_URI'].to_s, + operation: "#{req_method}:#{request.env['REQUEST_URI']}", carrier: carrier, inherit: Tracing::Component::General ) do |span| span&.tag(Tracing::TagHttpMethod.new(req_method)) span&.tag(Tracing::TagHttpURL.new(request.env['REQUEST_URI'])) - span&.layer = Tracing.find_mapping(Tracing::Layer, Tracing::Layer::Http) + span&.layer = Tracing::Layer::Http span&.peer = "#{request.env['SERVER_NAME']}:#{request.env['SERVER_PORT']}" span&.component = Tracing::Component::Sinatra diff --git a/lib/skywalking/reporter/buffer_trigger.rb b/lib/skywalking/reporter/buffer_trigger.rb index 1bab953..955d6a0 100644 --- a/lib/skywalking/reporter/buffer_trigger.rb +++ b/lib/skywalking/reporter/buffer_trigger.rb @@ -83,7 +83,7 @@ def generate_segment(segment) endTime: span.end_time, operationName: span.operation, peer: span.peer, - spanType: Tracing.find_mapping(Tracing::Kind, span.kind), + spanType: span.kind, spanLayer: span.layer, componentId: span.component, refs: span.refs.select { |ref| ref.trace_id }.map do |ref| diff --git a/lib/skywalking/reporter/client/grpc_client.rb b/lib/skywalking/reporter/client/grpc_client.rb index 5e51b58..2d32df1 100644 --- a/lib/skywalking/reporter/client/grpc_client.rb +++ b/lib/skywalking/reporter/client/grpc_client.rb @@ -26,7 +26,7 @@ class ManagementServiceGrpc def initialize(config) @config = config @management_service ||= ManagementServiceStub.new( - @config[:collector_backend_service], + @config[:collector_backend_services], :this_channel_is_insecure ) end @@ -97,7 +97,7 @@ class TraceSegmentReportServiceGrpc def initialize(config) @config = config @trace_service ||= TraceSegmentReportServiceStub.new( - @config[:collector_backend_service], + @config[:collector_backend_services], :this_channel_is_insecure ) end diff --git a/lib/skywalking/reporter/report.rb b/lib/skywalking/reporter/report.rb index ce536b6..6c397d5 100644 --- a/lib/skywalking/reporter/report.rb +++ b/lib/skywalking/reporter/report.rb @@ -14,7 +14,7 @@ # limitations under the License. require_relative 'grpc' -require_relative 'Scheduler' +require_relative 'scheduler' require_relative 'buffer_trigger' module Skywalking diff --git a/lib/skywalking/tracing/carrier.rb b/lib/skywalking/tracing/carrier.rb index 75ec4b7..d53472e 100644 --- a/lib/skywalking/tracing/carrier.rb +++ b/lib/skywalking/tracing/carrier.rb @@ -20,7 +20,8 @@ module Skywalking module Tracing class Carrier < CarrierItem attr_reader :trace_id, :correlation_carrier, :service_instance, - :endpoint, :segment_id, :span_id, :peer + :endpoint, :segment_id, :span_id, + :peer, :items, :iter_index def initialize( trace_id: '', @@ -47,7 +48,7 @@ def initialize( @correlation_carrier.correlation = correlation unless correlation.nil? end - def val + def value [ '1', Base64.strict_encode64(@trace_id), @@ -56,11 +57,11 @@ def val Base64.strict_encode64(@service), Base64.strict_encode64(@service_instance), Base64.strict_encode64(@endpoint), - Base64.strict_encode64(@client_address) + Base64.strict_encode64(@peer) ].join('-') end - def val=(val) + def value=(val) @val = val return if val.nil? || val.empty? @@ -73,13 +74,13 @@ def val=(val) @service = Base64.strict_decode64(parts[4]) @service_instance = Base64.strict_decode64(parts[5]) @endpoint = Base64.strict_decode64(parts[6]) - @client_address = Base64.strict_decode64(parts[7]) + @peer = Base64.strict_decode64(parts[7]) end def valid? !@trace_id.empty? && !@segment_id.empty? && !@service.empty? && !@service_instance.empty? && !@endpoint.empty? && - !@client_address.empty? && @span_id.match?(/^\d+$/) + !@peer.empty? && @span_id.match?(/^\d+$/) end def suppressed? @@ -99,13 +100,13 @@ def initialize @correlation = {} end - def val + def value return '' if @correlation.nil? || @correlation.empty? @correlation.map { |k, v| "#{Base64.strict_encode64(k)}:#{Base64.strict_encode64(v)}" }.join(',') end - def val=(val) + def value=(val) @val = val return if val.nil? || val.empty? diff --git a/lib/skywalking/tracing/constants.rb b/lib/skywalking/tracing/constants.rb index da5cd1d..6c3422c 100644 --- a/lib/skywalking/tracing/constants.rb +++ b/lib/skywalking/tracing/constants.rb @@ -17,33 +17,26 @@ module Skywalking module Tracing module Component Unknown = 0 + Http = 2 Redis = 7 General = 12000 Sinatra = 12001 end module Layer - Unknown = 0 - Database = 1 - RPCFramework = 2 - Http = 3 - MQ = 4 - Cache = 5 - FAAS = 6 + Unknown = "Unknown".freeze + Database = "Database".freeze + RPCFramework = "RPCFramework".freeze + Http = "Http".freeze + MQ = "MQ".freeze + Cache = "Cache".freeze + FAAS = "FAAS".freeze end module Kind - Local = 0 - Entry = 1 - Exit = 2 - end - - def self.find_mapping(category, value) - category.constants.each do |const_name| - return const_name if category.const_get(const_name) == value - end - - 'Unknown' + Local = "Local".freeze + Entry = "Entry".freeze + Exit = "Exit".freeze end end end diff --git a/lib/skywalking/tracing/noop_span.rb b/lib/skywalking/tracing/noop_span.rb index 7b27912..ea01750 100644 --- a/lib/skywalking/tracing/noop_span.rb +++ b/lib/skywalking/tracing/noop_span.rb @@ -19,7 +19,7 @@ module Skywalking module Tracing class NoopSpan < Span def initialize(context: nil) - super(context: context, operation: '', kind: Tracing::Kind::EXIT) + super(context: context, operation: '', kind: Kind::Exit) end def extract(carrier) end diff --git a/lib/skywalking/tracing/span.rb b/lib/skywalking/tracing/span.rb index bd03500..1f18760 100644 --- a/lib/skywalking/tracing/span.rb +++ b/lib/skywalking/tracing/span.rb @@ -21,7 +21,7 @@ module Skywalking module Tracing class Span attr_accessor :operation, :inherit, :component, - :context, :tags, :peer, :layer + :context, :tags, :peer, :layer, :error_occurred attr_reader :stack_depth, :kind, :parent_id, :start_time, :end_time, :span_id, :refs diff --git a/lib/skywalking/tracing/span_context.rb b/lib/skywalking/tracing/span_context.rb index 2718736..52c0cd1 100644 --- a/lib/skywalking/tracing/span_context.rb +++ b/lib/skywalking/tracing/span_context.rb @@ -87,7 +87,7 @@ def new_entry_span(operation, carrier: nil, inherit: nil) return span if span parent = peek - info 'create new entry span' + debug 'create new entry span' if parent && parent.kind == Kind::Entry && inherit == parent.component span = parent span.operation = operation @@ -104,7 +104,7 @@ def new_local_span(operation) return span if span parent = peek - info 'create new local span' + debug 'create new local span' new_span(Span, parent, operation: operation, kind: Kind::Local) end @@ -113,7 +113,7 @@ def new_exit_span(operation, peer, component: nil, inherit: nil) return span if span parent = peek - info 'create new exit span' + debug 'create new exit span' if parent && parent.kind == Kind::Exit && inherit == parent.inherit span = parent diff --git a/lib/skywalking/tracing/tag.rb b/lib/skywalking/tracing/tag.rb index 1f6f858..2cf348d 100644 --- a/lib/skywalking/tracing/tag.rb +++ b/lib/skywalking/tracing/tag.rb @@ -31,7 +31,7 @@ def initialize(val) @key = 'http.method' end end - + class TagHttpURL < Tag def initialize(val) super @@ -39,11 +39,46 @@ def initialize(val) end end + class TagHttpStatusCode < Tag + def initialize(val) + super + @key = 'http.status_code' + end + end + class TagDbType < Tag def initialize(val) super @key = 'db.type' end end + + class TagCacheType < Tag + def initialize(val) + super + @key = 'cache.type' + end + end + + class TagCacheOp < Tag + def initialize(val) + super + @key = 'cache.op' + end + end + + class TagCacheCmd < Tag + def initialize(val) + super + @key = 'cache.cmd' + end + end + + class TagCacheKey < Tag + def initialize(val) + super + @key = 'cache.key' + end + end end end diff --git a/lib/skywalking/version.rb b/lib/skywalking/version.rb index 3202b14..feec054 100644 --- a/lib/skywalking/version.rb +++ b/lib/skywalking/version.rb @@ -14,5 +14,5 @@ # limitations under the License. module Skywalking - VERSION = "0.0.0-rc".freeze + VERSION = "0.0.0.beta1".freeze end diff --git a/skywalking.gemspec b/skywalking.gemspec index f10ae85..cef22fc 100644 --- a/skywalking.gemspec +++ b/skywalking.gemspec @@ -13,44 +13,49 @@ # See the License for the specific language governing permissions and # limitations under the License. -require File.expand_path("lib/skywalking/version", __dir__) +require File.expand_path('lib/skywalking/version', __dir__) Gem::Specification.new do |spec| - spec.name = "skywalking" + spec.name = 'skywalking' spec.version = Skywalking::VERSION - spec.authors = ["Apache SkyWalking Team"] - spec.email = ["dev@skywalking.apache.org"] + spec.authors = ['Apache SkyWalking Team'] + spec.email = ['dev@skywalking.apache.org'] - spec.summary = "Skywalking Ruby" - spec.description = "The Ruby Agent for Apache SkyWalking" - spec.homepage = "https://skywalking.apache.org/" - spec.license = "Apache-2.0" - spec.required_ruby_version = ">= 3.0.0" + spec.summary = 'Skywalking Ruby Agent' + spec.description = 'The Ruby Agent for Apache SkyWalking' + spec.homepage = 'https://skywalking.apache.org/' + spec.license = 'Apache-2.0' + spec.required_ruby_version = '>= 3.0.0' spec.metadata["homepage_uri"] = spec.homepage - spec.metadata["source_code_uri"] = "https://github.com/apache/skywalking-ruby" - spec.metadata["changelog_uri"] = "https://github.com/apache/skywalking-ruby/blob/main/CHANGELOG.md" - - # Specify which files should be added to the gem when it is released. - # The `git ls-files -z` loads the files in the RubyGem that have been added into git. - gemspec = File.basename(__FILE__) - spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| - ls.readlines("\x0", chomp: true).reject do |f| - (f == gemspec) || - f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) + spec.metadata["source_code_uri"] = 'https://github.com/apache/skywalking-ruby' + spec.metadata["changelog_uri"] = 'https://github.com/apache/skywalking-ruby/blob/main/CHANGELOG.md' + + files = + begin + `git ls-files`.split("\n") + rescue StandardError + Dir.glob("**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) } end - end - spec.bindir = "exe" + spec.files = files spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } - spec.require_paths = ["lib"] - - # Uncomment to register a new dependency of your gem - spec.add_development_dependency "bundler" - spec.add_development_dependency "rake" - spec.add_development_dependency "rspec" - spec.add_development_dependency "rubocop" - spec.add_development_dependency "rubocop-performance" - spec.add_development_dependency "grpc" - spec.add_development_dependency "grpc-tools" - spec.add_development_dependency "rackup" + spec.require_paths = ['lib'] + + # Communication with OAP + spec.add_dependency 'grpc', '1.68.1' + + # Base dev dependency + spec.add_development_dependency 'bundler', '>= 2.0' + spec.add_development_dependency 'rake', '13.2.1' + spec.add_development_dependency 'rspec', '~> 3' + spec.add_development_dependency 'rubocop', '1.69.2' + spec.add_development_dependency 'rubocop-performance', '1.23.0' + spec.add_development_dependency 'bigdecimal', '3.1.5' + + # E2E test dependency + spec.add_development_dependency 'redis', '~> 5.0' + spec.add_development_dependency 'sinatra', '~> 4.1' + spec.add_development_dependency 'testcontainers-compose', '~> 0.2.0' + spec.add_development_dependency 'faraday', '~> 2.12' + spec.add_development_dependency 'rspec-wait', '~> 1.0' end diff --git a/spec/fixtures/agent.yaml b/spec/fixtures/agent.yaml index 39ee566..7948e7c 100644 --- a/spec/fixtures/agent.yaml +++ b/spec/fixtures/agent.yaml @@ -22,5 +22,5 @@ instance_name: Your_InstanceName # Whether to enable the reporter collector_discard: false # The gRPC server address of the backend service. -collector_backend_service: 127.0.0.1:11800 +collector_backend_services: 127.0.0.1:11800 config_file: config/skywalking.yaml \ No newline at end of file diff --git a/spec/scenarios/common/Dockerfile.agent b/spec/scenarios/common/Dockerfile.agent new file mode 100644 index 0000000..0178664 --- /dev/null +++ b/spec/scenarios/common/Dockerfile.agent @@ -0,0 +1,26 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ARG SW_RUBY_VERSION + +FROM ruby:${SW_RUBY_VERSION} + +ARG ROOT=. + +WORKDIR /app + +ADD $ROOT /app + +RUN bundle \ No newline at end of file diff --git a/spec/scenarios/common/base-compose.yml b/spec/scenarios/common/base-compose.yml new file mode 100644 index 0000000..2d338ba --- /dev/null +++ b/spec/scenarios/common/base-compose.yml @@ -0,0 +1,46 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +version: '2.1' + +services: + oap: + image: ghcr.io/apache/skywalking-agent-test-tool/mock-collector:b6efe6af0a5499502b8cf8b76c7351e3f172a616 + ports: + - "12800:12800" + - "19876:19876" + networks: + - gem + healthcheck: + test: [ "CMD", "bash", "-c", "cat < /dev/null > /dev/tcp/127.0.0.1/12800" ] + interval: 5s + timeout: 60s + retries: 120 + + agent: + build: + context: ../../../ + dockerfile: spec/scenarios/common/Dockerfile.agent + args: + - SW_RUBY_VERSION=${SW_RUBY_VERSION:-3.0} + environment: + SW_AGENT_COLLECTOR_BACKEND_SERVICES: oap:19876 + networks: + - gem + +networks: + gem: diff --git a/spec/scenarios/common/common_spec_helper.rb b/spec/scenarios/common/common_spec_helper.rb new file mode 100644 index 0000000..d16b68f --- /dev/null +++ b/spec/scenarios/common/common_spec_helper.rb @@ -0,0 +1,40 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require 'testcontainers/compose' +require 'faraday' +require_relative 'validator' + +module CommonSpecHelper + include Validator + + def test_plugin(plugin_name) + p "Now testing #{plugin_name} plugin" + expected_data = File.read(File.join(root_dir, 'expected.yml')) + + with_retries do + resp = Faraday.post(data_validate_url) do |req| + req.body = expected_data + req.headers['Content-Type'] = 'application/x-yaml' + end + unless resp.status == 200 + actual_data = Faraday.get(receive_data_url).body + raise "Data validation failed, actual Data: #{actual_data} and cause by: #{resp.body}" + end + end + end +end + + diff --git a/spec/scenarios/common/compose_context.rb b/spec/scenarios/common/compose_context.rb new file mode 100644 index 0000000..741291d --- /dev/null +++ b/spec/scenarios/common/compose_context.rb @@ -0,0 +1,39 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +RSpec.shared_context 'scenario value' do + let(:data_validate_url) { 'http://localhost:12800/dataValidate' } + let(:receive_data_url) { 'http://localhost:12800/receiveData' } +end + +RSpec.shared_context 'compose' do + let(:client_url) { 'http://localhost:8080/execute' } + + let(:compose) do + Testcontainers::ComposeContainer.new( + filepath: root_dir, + compose_filenames: ["docker-compose.yml"] + ) + end + + before(:each) do + compose.start + compose.wait_for_http(url: client_url, timeout: 600) + end + + after(:each) do + compose.stop + end +end \ No newline at end of file diff --git a/spec/scenarios/common/validator.rb b/spec/scenarios/common/validator.rb new file mode 100644 index 0000000..f420cbf --- /dev/null +++ b/spec/scenarios/common/validator.rb @@ -0,0 +1,41 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +module Validator + def with_retries(retries: 3, backoff_max: 16, backoff_base: 1) + return if retries < 0 + + backoff ||= 0 + + yield if block_given? + rescue SystemExit, Interrupt + raise + rescue Exception => e + p e + if retries.zero? + p "Retries exhausted" + raise e + else + retries -= 1 + backoff = [backoff == 0 ? 1 : backoff * 2, backoff_max].min + backoff *= 0.5 * (1 + Kernel.rand) + backoff = [backoff_base, backoff].max + p "Retrying in #{backoff} seconds" + + sleep backoff + retry + end + end +end \ No newline at end of file diff --git a/spec/scenarios/net_http/docker-compose.yml b/spec/scenarios/net_http/docker-compose.yml new file mode 100644 index 0000000..1c8e1b7 --- /dev/null +++ b/spec/scenarios/net_http/docker-compose.yml @@ -0,0 +1,49 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +version: "2.1" + +services: + oap: + extends: + file: ../common/base-compose.yml + service: oap + networks: + - gem + + service: + extends: + file: ../common/base-compose.yml + service: agent + ports: + - "8080:8080" + volumes: + - .:/app/spec/scenarios/net_http + environment: + SW_AGENT_SERVICE_NAME: "NetHttp" + entrypoint: + - "sh" + - "-c" + - "ruby /app/spec/scenarios/net_http/net_http.rb" + depends_on: + oap: + condition: service_healthy + networks: + - gem + +networks: + gem: \ No newline at end of file diff --git a/spec/scenarios/net_http/expected.yml b/spec/scenarios/net_http/expected.yml new file mode 100644 index 0000000..7e60d6b --- /dev/null +++ b/spec/scenarios/net_http/expected.yml @@ -0,0 +1,39 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +segmentItems: + - serviceName: NetHttp + segmentSize: ge 1 + segments: + - segmentId: not null + spans: + - operationName: "GET:/json?a=1" + parentSpanId: -1 + spanId: 0 + spanLayer: Http + startTime: gt 0 + endTime: gt 0 + componentId: 2 + isError: false + spanType: Exit + peer: httpbin.org + skipAnalysis: false + tags: + - { key: http.method, value: GET } + - { key: http.url, value: "http://httpbin.org/json?a=1" } + - { key: http.status_code, value: "200" } +meterItems: [ ] +logItems: [ ] \ No newline at end of file diff --git a/spec/scenarios/net_http/net_http.rb b/spec/scenarios/net_http/net_http.rb new file mode 100644 index 0000000..ee56e98 --- /dev/null +++ b/spec/scenarios/net_http/net_http.rb @@ -0,0 +1,33 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require_relative '../../../lib/skywalking' +require 'net/http' +require 'uri' +require 'json' + +Skywalking.start + +url = URI.parse('http://httpbin.org/json?a=1') + +response = Net::HTTP.get_response(url) + +if response.is_a?(Net::HTTPSuccess) + puts JSON.pretty_generate(JSON.parse(response.body)) +else + puts "Error..." +end + +sleep 10 \ No newline at end of file diff --git a/spec/scenarios/net_http/net_http_spec.rb b/spec/scenarios/net_http/net_http_spec.rb new file mode 100644 index 0000000..8e6df0b --- /dev/null +++ b/spec/scenarios/net_http/net_http_spec.rb @@ -0,0 +1,43 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require_relative '../common/common_spec_helper' +require_relative '../common/compose_context' + +RSpec.describe 'NetHttp' do + include CommonSpecHelper + include_context 'scenario value' + + let(:root_dir) { File.expand_path(__dir__) } + + let(:compose) do + Testcontainers::ComposeContainer.new( + filepath: root_dir, + compose_filenames: ["docker-compose.yml"] + ) + end + + before(:each) do + compose.start + end + + after(:each) do + compose.stop + end + + it 'test the net_http plugin' do + test_plugin('net_http') + end +end diff --git a/spec/scenarios/redis/docker-compose.yml b/spec/scenarios/redis/docker-compose.yml new file mode 100644 index 0000000..bf34ccd --- /dev/null +++ b/spec/scenarios/redis/docker-compose.yml @@ -0,0 +1,67 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +version: "2.1" + +services: + oap: + extends: + file: ../common/base-compose.yml + service: oap + networks: + - gem + + redis: + image: redis:7-alpine + hostname: redis + ports: + - "6379:6379" + healthcheck: + test: [ "CMD", "bash", "-c", "cat < /dev/null > /dev/tcp/127.0.0.1/6379" ] + interval: 5s + timeout: 60s + retries: 120 + networks: + - gem + + service: + extends: + file: ../common/base-compose.yml + service: agent + ports: + - "8080:8080" + volumes: + - .:/app/spec/scenarios/redis + environment: + SW_AGENT_SERVICE_NAME: "redis" + healthcheck: + test: [ "CMD", "bash", "-c", "cat < /dev/null > /dev/tcp/127.0.0.1/8080" ] + interval: 5s + timeout: 60s + retries: 120 + entrypoint: + - "sh" + - "-c" + - "gem install sinatra rackup puma redis && ruby /app/spec/scenarios/redis/redis.rb" + depends_on: + oap: + condition: service_healthy + networks: + - gem + +networks: + gem: \ No newline at end of file diff --git a/spec/scenarios/redis/expected.yml b/spec/scenarios/redis/expected.yml new file mode 100644 index 0000000..731bc75 --- /dev/null +++ b/spec/scenarios/redis/expected.yml @@ -0,0 +1,66 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +segmentItems: + - serviceName: redis + segmentSize: ge 1 + segments: + - segmentId: not null + spans: + - operationName: Redis/SET + parentSpanId: 0 + spanId: 1 + spanLayer: Cache + startTime: gt 0 + endTime: gt 0 + componentId: 7 + isError: false + spanType: Exit + peer: redis:6379 + skipAnalysis: false + tags: + - { key: cache.type, value: Redis } + - { key: cache.op, value: set } + - operationName: Redis/GET + parentSpanId: 0 + spanId: 2 + spanLayer: Cache + startTime: gt 0 + endTime: gt 0 + componentId: 7 + isError: false + spanType: Exit + peer: redis:6379 + skipAnalysis: false + tags: + - { key: cache.type, value: Redis } + - { key: cache.op, value: get } + - operationName: GET:/execute + parentSpanId: -1 + spanId: 0 + spanLayer: Http + startTime: gt 0 + endTime: gt 0 + componentId: 12001 + isError: false + spanType: Entry + peer: localhost:8080 + skipAnalysis: false + tags: + - { key: http.method, value: GET } + - { key: http.url, value: /execute } +meterItems: [ ] +logItems: [ ] \ No newline at end of file diff --git a/spec/scenarios/redis/redis.rb b/spec/scenarios/redis/redis.rb new file mode 100644 index 0000000..5eed8ac --- /dev/null +++ b/spec/scenarios/redis/redis.rb @@ -0,0 +1,30 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require 'sinatra' +require 'redis' +require_relative '../../../lib/skywalking' + +Skywalking.start + +get '/execute' do + redis = Redis.new(host: 'redis', port: 6379) + redis.set('hello', 'world') + value = redis.get("hello") + "Hello #{value}!" +end + +set :bind, '0.0.0.0' +set :port, 8080 \ No newline at end of file diff --git a/spec/scenarios/redis/redis_spec.rb b/spec/scenarios/redis/redis_spec.rb new file mode 100644 index 0000000..cd1bacb --- /dev/null +++ b/spec/scenarios/redis/redis_spec.rb @@ -0,0 +1,29 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require_relative '../common/common_spec_helper' +require_relative '../common/compose_context' + +RSpec.describe 'Redis' do + include CommonSpecHelper + include_context 'compose' + include_context 'scenario value' + + let(:root_dir) { File.expand_path(__dir__) } + + it 'test redis plugin' do + test_plugin('redis') + end +end diff --git a/spec/scenarios/sinatra/docker-compose.yml b/spec/scenarios/sinatra/docker-compose.yml new file mode 100644 index 0000000..af556b4 --- /dev/null +++ b/spec/scenarios/sinatra/docker-compose.yml @@ -0,0 +1,54 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +version: "2.1" + +services: + oap: + extends: + file: ../common/base-compose.yml + service: oap + networks: + - gem + + service: + extends: + file: ../common/base-compose.yml + service: agent + ports: + - "8080:8080" + volumes: + - .:/app/spec/scenarios/sinatra + environment: + SW_AGENT_SERVICE_NAME: "sinatra" + healthcheck: + test: [ "CMD", "bash", "-c", "cat < /dev/null > /dev/tcp/127.0.0.1/8080" ] + interval: 5s + timeout: 60s + retries: 120 + entrypoint: + - "sh" + - "-c" + - "gem install sinatra rackup puma && ruby /app/spec/scenarios/sinatra/sinatra.rb" + depends_on: + oap: + condition: service_healthy + networks: + - gem + +networks: + gem: \ No newline at end of file diff --git a/spec/scenarios/sinatra/expected.yml b/spec/scenarios/sinatra/expected.yml new file mode 100644 index 0000000..2ac9b9a --- /dev/null +++ b/spec/scenarios/sinatra/expected.yml @@ -0,0 +1,38 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +segmentItems: + - serviceName: sinatra + segmentSize: ge 1 + segments: + - segmentId: not null + spans: + - operationName: GET:/execute + parentSpanId: -1 + spanId: 0 + spanLayer: Http + startTime: gt 0 + endTime: gt 0 + componentId: 12001 + isError: false + spanType: Entry + peer: localhost:8080 + skipAnalysis: false + tags: + - { key: http.method, value: GET } + - { key: http.url, value: /execute } +meterItems: [ ] +logItems: [ ] \ No newline at end of file diff --git a/examples/rails-demo/config/initializers/skywalking_ruby.rb b/spec/scenarios/sinatra/sinatra.rb similarity index 83% rename from examples/rails-demo/config/initializers/skywalking_ruby.rb rename to spec/scenarios/sinatra/sinatra.rb index 92256cf..42047df 100644 --- a/examples/rails-demo/config/initializers/skywalking_ruby.rb +++ b/spec/scenarios/sinatra/sinatra.rb @@ -13,6 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -require_relative '../../../../lib/skywalking' +require_relative '../../../lib/skywalking' +require 'sinatra' -Skywalking.start \ No newline at end of file +Skywalking.start + +get "/execute" do + "Hello, SkyWalking!" +end + +set :bind, '0.0.0.0' +set :port, 8080 \ No newline at end of file diff --git a/spec/scenarios/sinatra/sinatra_spec.rb b/spec/scenarios/sinatra/sinatra_spec.rb new file mode 100644 index 0000000..8fb3d23 --- /dev/null +++ b/spec/scenarios/sinatra/sinatra_spec.rb @@ -0,0 +1,29 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require_relative '../common/common_spec_helper' +require_relative '../common/compose_context' + +RSpec.describe "Sinatra" do + include CommonSpecHelper + include_context 'compose' + include_context 'scenario value' + + let(:root_dir) { File.expand_path(__dir__) } + + it 'test sinatra plugin' do + test_plugin('sinatra') + end +end \ No newline at end of file diff --git a/spec/skywalking_ruby/config_spec.rb b/spec/skywalking/config_spec.rb similarity index 69% rename from spec/skywalking_ruby/config_spec.rb rename to spec/skywalking/config_spec.rb index e13df0c..7f135da 100644 --- a/spec/skywalking_ruby/config_spec.rb +++ b/spec/skywalking/config_spec.rb @@ -18,24 +18,24 @@ module Skywalking RSpec.describe Configuration do it 'load DEFAULTS' do - config = Configuration.new - expect(config.service_name).to eq 'Your_ApplicationName' + config = Configuration.new.agent_config + expect(config[:service_name]).to eq 'Your_ApplicationName' end it 'loads args' do - config = Configuration.new(service_name: 'sw-ruby') - expect(config.service_name).to eq 'sw-ruby' + config = Configuration.new(service_name: 'sw-ruby').agent_config + expect(config[:service_name]).to eq 'sw-ruby' end it 'loads from yaml' do - config = Configuration.new(config_file: 'spec/fixtures/agent.yaml') - expect(config.service_name).to eq 'sw-ruby' + config = Configuration.new(config_file: 'spec/fixtures/agent.yaml').agent_config + expect(config[:service_name]).to eq 'sw-ruby' end it 'loads from env' do - ENV['SW_AGENT_SERVICE_NAME'] = 'sw-ruby-env' - config = Configuration.new - expect(config.service_name).to eq 'sw-ruby-env' + ENV['SW_AGENT_COLLECTOR_BACKEND_SERVICES'] = 'oap:11800' + config = Configuration.new.agent_config + expect(config[:collector_backend_services]).to eq 'oap:11800' end end end \ No newline at end of file diff --git a/spec/skywalking_ruby/utils/id_gen_spec.rb b/spec/skywalking/utils/id_gen_spec.rb similarity index 100% rename from spec/skywalking_ruby/utils/id_gen_spec.rb rename to spec/skywalking/utils/id_gen_spec.rb diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1a5ae73..81ef90a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause