zgcp_toolkit 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fdd5f30aab3e292d7eefa9c362a0e79129cfc39d48c85b74822377d80a30cd91
4
+ data.tar.gz: 8f0e40f5d92bad0d83c8e856b2d81d1dc347987fb28e1e963cdeb8e29d855b3d
5
+ SHA512:
6
+ metadata.gz: 462b117371427824f07fc8caf86b9d2af58e3304ebf38081e687e8c39264981a674600da0c6c69de9150d33a8975d7956af05ceab1a8ecd05d2f648d270a5590
7
+ data.tar.gz: be469a18442677b5ffddc406e029941c6cda7d9daa596d227f4785960d0f3e1801a7c49f28b5500ddd0d8caa80d8b56f4c0d06b7682ae89f833bf844b93d0e66
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /*.gem
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.7.2
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at hungnt@zigexn.vn. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in zgcp_toolkit.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Ngo Trung Hung
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # GCP Toolkit
2
+ Manage integration between Rails & Google Cloud services.
3
+
4
+ ## Installation
5
+
6
+ Add this line to your application's Gemfile:
7
+
8
+ ```ruby
9
+ gem 'zgcp_toolkit'
10
+ ```
11
+
12
+ And then execute:
13
+
14
+ $ bundle install
15
+
16
+ Or install it yourself as:
17
+
18
+ $ gem install zgcp_toolkit
19
+
20
+ Next, you need to run the generator:
21
+
22
+ $ rails generate zgcp_toolkit
23
+
24
+ ## Logger
25
+ Each rake task will have its own log file in Cloud Logging. The log file name on Cloud Logging are combined from the rake task `namespace`s and `task name`. The rake task also be able to access the logger object.
26
+
27
+ Unexpected errors in rake tasks are caught automatically & write to a log file in Cloud Logging. And, by default, when GCP Toolkit caught an unexpected error, it push a key & value (key: `push_slack` with value: `true`) in Cloud Logging Log `jsonPayload` so that the log that should be sent on Slack can be filtered.
28
+
29
+ ### Usage
30
+
31
+ ```ruby
32
+ namespace :tcv_transactions do
33
+ task :daily_import do |t, logger:|
34
+ logger.info("Heyyyyyy!")
35
+ # The error message & backtrace are sent to Cloud Logging
36
+ raise "Heyyyyyy Oops!"
37
+ end
38
+ end
39
+ ```
40
+
41
+ ```ruby
42
+ logger = ZgcpToolkit::Logger.new(:any_log_name)
43
+ logger.info("Heyyyyyy!")
44
+ logger.error(message: "Heyyyyy!", backtrace: ["line-1", "line-2"])
45
+ logger.error(message: "Hello Bug !!", backtrace: ["line-1", "line-2"], push_slack: true)
46
+ logger.warn("Hey hey nyc!")
47
+ ```
48
+
49
+ - Set `send_unexpected_error_to_slack` to `false` will delete `push_slack` key from unexpected error log.
50
+
51
+ ```ruby
52
+ namespace :test_log do
53
+ task do: :environment do |args, logger:|
54
+ logger.send_unexpected_error_to_slack = false
55
+ raise 'errors'
56
+ end
57
+ end
58
+ ```
59
+
60
+ ### Controller
61
+
62
+ you can send controller errors to Google Cloud Loggings
63
+
64
+ ```ruby
65
+ # app/controllers/application_controller.rb
66
+
67
+ rescue_from StandardError do |e|
68
+ raise e if Rails.env.development?
69
+
70
+ logger = ZgcpToolkit::Logger.new(Rails.env)
71
+ logger.error_request(e, request)
72
+
73
+ # If you want send notity to slack
74
+ # logger.error_request(e, request, push_slack: true)
75
+
76
+ head :internal_server_error
77
+ end
78
+
79
+ ```
80
+
81
+ ### Note on using Pub/Sub and Cloud Function to deliver log to your Slack channel
82
+
83
+ - Function invocations are charged at a flat rate regardless of the source of the invocation. This includes HTTP function invocations from HTTP requests, events forwarded to background or CloudEvent functions, and invocations resulting from the call API.
84
+
85
+ - When GCP filter log to sink to Cloud Pub/Sub topic it will use CloudEvent event function so that will also count as an invocation.
86
+
87
+ - When logging from the rails app, you should log error levels or higher to reduce costs.
88
+
89
+ - For sending a Slack notification when a training task gets completed, a possible solution might be setting up a Pub/Sub sink for matching logs from Cloud Logging to be sent to. Details here in Exporting logs with the Google Cloud Console. If a log matches the sink’s query (look for all training status updates from AI Platform), then Cloud Logging will send the log directly to the indicated Pub/Sub topic and extra VM is not needed for this.
90
+
91
+ - After sending the messages to a Pub/Sub topic, you can set up a Cloud Function to post messages to Slack (and/or to email you) when the logs indicate that the AI Platform training job is done. Please note that the Cloud Function will only run when a relevant log is posted to Pub/Sub.Details on Google Cloud Pub/Sub Triggers and Configuring Slack notifications.
92
+
93
+ ### References
94
+ - https://cloud.google.com/functions/docs/calling/pubsub
95
+ - https://cloud.google.com/logging/docs/export/configure_export_v2
96
+ - https://cloud.google.com/cloud-build/docs/configure-third-party-notifications#slack_notifications
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "zgcp_toolkit"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ require "zgcp_toolkit/version"
2
+
3
+ module ZgcpToolkit; end
4
+
5
+ require 'zgcp_toolkit/logger'
6
+ require 'zgcp_toolkit/rake/task'
7
+ require 'zgcp_toolkit/generators/templates/zgcp_toolkit'
8
+ require 'zgcp_toolkit/generators/zgcp_toolkit_generator'
@@ -0,0 +1,11 @@
1
+ require 'dry/configurable'
2
+ require 'google/cloud/logging'
3
+ require 'rake/task'
4
+
5
+ Rake::Task.prepend(ZgcpToolkit::Rake::Task)
6
+
7
+ loggers = [:std_out]
8
+
9
+ loggers.push(:google_cloud_logging) unless Rails.env.development?
10
+
11
+ ZgcpToolkit::Logger.config.registered_loggers = loggers
@@ -0,0 +1,9 @@
1
+ require 'rails/generators'
2
+
3
+ class ZgcpToolkitGenerator < Rails::Generators::Base
4
+ source_root File.expand_path("../templates", __FILE__)
5
+
6
+ def copy_initializer
7
+ template "zgcp_toolkit.rb", "config/initializers/zgcp_toolkit.rb"
8
+ end
9
+ end
@@ -0,0 +1,104 @@
1
+ require 'dry/configurable'
2
+ require 'zgcp_toolkit/logger/stdout'
3
+ require 'zgcp_toolkit/logger/google_cloud_logging'
4
+
5
+ module ZgcpToolkit
6
+ class Logger
7
+ extend Dry::Configurable
8
+
9
+ AVAILABLE_LOGGERS = {
10
+ std_out: ZgcpToolkit::Logger::Stdout,
11
+ google_cloud_logging: ZgcpToolkit::Logger::GoogleCloudLogging
12
+ }
13
+
14
+ setting :registered_loggers, [:std_out, :google_cloud_logging], reader: true do |logger_names|
15
+ logger_names.map { |n| AVAILABLE_LOGGERS[n] }
16
+ end
17
+
18
+ class Error < StandardError; end
19
+ class UnsupportedLogType < Error; end
20
+
21
+ DEFAULT_BACKTRACE_LIMIT = 10
22
+
23
+ attr_accessor :send_unexpected_error_to_slack, :backtrace_limit
24
+ attr_reader :loggers, :log_name
25
+
26
+ def initialize(log_name)
27
+ @log_name = log_name
28
+ @send_unexpected_error_to_slack = true
29
+ @backtrace_limit = DEFAULT_BACKTRACE_LIMIT
30
+ @loggers = ZgcpToolkit::Logger.registered_loggers.map { |logger| logger.new(log_name) }
31
+ end
32
+
33
+ [:debug, :info, :warn, :error, :fatal, :unknown].each do |log_level_method|
34
+ define_method(log_level_method) do |log, push_slack: false|
35
+ log_object =
36
+ case log
37
+ when StandardError
38
+ obj = { message: log.message, backtrace: log.backtrace.first(backtrace_limit) }
39
+ obj.merge!(push_slack: true) if push_slack
40
+ obj
41
+ when Hash
42
+ log
43
+ when String
44
+ obj = { message: log }
45
+ obj.merge!(push_slack: true) if push_slack
46
+ obj
47
+ else
48
+ raise UnsupportedLogType, "#{log.class.name} is not supported!"
49
+ end
50
+ loggers.each { |a| a.send(log_level_method, log_object) }
51
+ end
52
+ end
53
+
54
+ def error_request(error, request, **args)
55
+ filter_request_params = format_request_env(request)
56
+
57
+ error({ message: error.message, backtrace: error.backtrace.first(backtrace_limit) }.merge!(filter_request_params).merge!(args))
58
+ end
59
+
60
+ def flush!
61
+ loggers.each { |a| a.flush! }
62
+ end
63
+
64
+ private
65
+
66
+ def format_request_env(request)
67
+ log_object = {}
68
+ log_object[:request] = request_filter(request)
69
+ log_object[:session] = session_filter(request)
70
+ log_object[:environment] = environment_filter(request)
71
+ log_object
72
+ end
73
+
74
+ def environment_filter(request)
75
+ result = {}
76
+ request.filtered_env.keys.each do |key|
77
+ result[key] = request.filtered_env[key]
78
+ end
79
+ result
80
+ end
81
+
82
+ def session_filter(request)
83
+ result = {}
84
+ result[:session_id] = request.ssl? ? "[FILTERED]" : request.session['session_id'] || request.env['rack.session.options'][:id].inspect
85
+ result[:data_session] = request.session.to_hash
86
+ result
87
+ end
88
+
89
+ def request_filter(request)
90
+ result = {}
91
+ result[:url] = request.url
92
+ result[:request_method] = request.request_method
93
+ result[:ip_address] = request.remote_ip
94
+ result[:parameters] = request.filtered_parameters.inspect
95
+ result[:timestamp] = Time.current
96
+ result[:server] = Socket.gethostname
97
+ result[:process] = $$
98
+ if defined?(Rails) && Rails.respond_to?(:root)
99
+ result[:rails_root] = Rails.root
100
+ end
101
+ result
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,20 @@
1
+ module ZgcpToolkit
2
+ class Logger
3
+ class GoogleCloudLogging
4
+ attr_reader :logger, :log_name
5
+
6
+ delegate :debug, :info, :warn, :error, :fatal, :unknown, to: :logger
7
+
8
+ def initialize(log_name)
9
+ @log_name = log_name.to_s
10
+ logging = Google::Cloud::Logging.new
11
+ resource = Google::Cloud::Logging::Middleware.build_monitored_resource
12
+ @logger = logging.logger @log_name, resource
13
+ end
14
+
15
+ def flush!
16
+ logger.writer.async_stop!
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,24 @@
1
+ require 'logger'
2
+
3
+ module ZgcpToolkit
4
+ class Logger
5
+ class Stdout
6
+ attr_reader :logger, :log_name
7
+
8
+ def initialize(log_name)
9
+ @log_name = log_name.to_s
10
+ @logger = ::Logger.new(STDOUT)
11
+ end
12
+
13
+ [:debug, :info, :warn, :error, :fatal, :unknown].each do |log_level_method|
14
+ define_method(log_level_method) do |log|
15
+ logger.send(log_level_method, "#{log_name} -- #{log}")
16
+ end
17
+ end
18
+
19
+ def flush!
20
+ # no-op
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,13 @@
1
+ module ZgcpToolkit::Rake
2
+ module Task
3
+ def execute(args=nil)
4
+ task_name = self.name.gsub(':', '_')
5
+ logger = ZgcpToolkit::Logger.new(task_name)
6
+ args.with_defaults(logger: logger)
7
+ super
8
+ rescue StandardError => e
9
+ logger.error(e, push_slack: logger.send_unexpected_error_to_slack)
10
+ logger.flush!
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,3 @@
1
+ module ZgcpToolkit
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,27 @@
1
+ require_relative 'lib/zgcp_toolkit/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "zgcp_toolkit"
5
+ spec.version = ZgcpToolkit::VERSION
6
+ spec.authors = "ZIGExN VeNtura developers"
7
+ spec.email = "kuruma-dev@zigexn.vn"
8
+
9
+ spec.summary = "GCP Toolkit"
10
+ spec.description = "Manage essential toolset"
11
+ spec.homepage = "https://github.com/ZIGExN/zgcp_toolkit"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+
18
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
19
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ end
21
+ spec.bindir = "exe"
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_dependency 'stackdriver', '~> 0.20.1'
26
+ spec.add_dependency 'dry-configurable', '~> 0.11.6'
27
+ end
metadata ADDED
@@ -0,0 +1,91 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: zgcp_toolkit
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - ZIGExN VeNtura developers
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-06-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: stackdriver
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.20.1
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.20.1
27
+ - !ruby/object:Gem::Dependency
28
+ name: dry-configurable
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.11.6
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.11.6
41
+ description: Manage essential toolset
42
+ email: kuruma-dev@zigexn.vn
43
+ executables: []
44
+ extensions: []
45
+ extra_rdoc_files: []
46
+ files:
47
+ - ".gitignore"
48
+ - ".rspec"
49
+ - ".travis.yml"
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - bin/console
56
+ - bin/setup
57
+ - lib/zgcp_toolkit.rb
58
+ - lib/zgcp_toolkit/generators/templates/zgcp_toolkit.rb
59
+ - lib/zgcp_toolkit/generators/zgcp_toolkit_generator.rb
60
+ - lib/zgcp_toolkit/logger.rb
61
+ - lib/zgcp_toolkit/logger/google_cloud_logging.rb
62
+ - lib/zgcp_toolkit/logger/stdout.rb
63
+ - lib/zgcp_toolkit/rake/task.rb
64
+ - lib/zgcp_toolkit/version.rb
65
+ - zgcp_toolkit.gemspec
66
+ homepage: https://github.com/ZIGExN/zgcp_toolkit
67
+ licenses:
68
+ - MIT
69
+ metadata:
70
+ allowed_push_host: https://rubygems.org
71
+ homepage_uri: https://github.com/ZIGExN/zgcp_toolkit
72
+ post_install_message:
73
+ rdoc_options: []
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: 2.3.0
81
+ required_rubygems_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ requirements: []
87
+ rubygems_version: 3.1.4
88
+ signing_key:
89
+ specification_version: 4
90
+ summary: GCP Toolkit
91
+ test_files: []