sillydev 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +56 -6
- data/lib/sillydev/cli.rb +510 -3
- data/lib/sillydev/client.rb +35 -8
- data/lib/sillydev/console.rb +17 -0
- data/lib/sillydev/errors.rb +24 -4
- data/lib/sillydev/mcp_server.rb +255 -10
- data/lib/sillydev/monitoring/client.rb +23 -3
- data/lib/sillydev/monitoring/runtime.rb +5 -5
- data/lib/sillydev/monitoring.rb +11 -1
- data/lib/sillydev/resources.rb +365 -27
- data/lib/sillydev/version.rb +1 -1
- metadata +2 -2
data/lib/sillydev/client.rb
CHANGED
|
@@ -17,7 +17,8 @@ module SillyDev
|
|
|
17
17
|
DEFAULT_BASE_URL = "https://sillydev.co.uk/panel/api/client"
|
|
18
18
|
DEFAULT_TIMEOUT = 60
|
|
19
19
|
DEFAULT_MAX_RETRIES = 2
|
|
20
|
-
RETRY_STATUSES = [429, 502, 503, 504].freeze
|
|
20
|
+
RETRY_STATUSES = [408, 429, 502, 503, 504].freeze
|
|
21
|
+
LOOPBACK = %w[localhost 127.0.0.1 ::1 [::1]].freeze
|
|
21
22
|
# A POST answered 502, 503 or 504 may still have reached the server: the node can have run the
|
|
22
23
|
# command or the power action before the gateway gave up. Only 429, which is refused before
|
|
23
24
|
# anything runs, is safe to retry for those, unless the request carries an Idempotency-Key
|
|
@@ -25,14 +26,20 @@ module SillyDev
|
|
|
25
26
|
UNSAFE_RETRY_STATUSES = [429].freeze
|
|
26
27
|
SAFE_METHODS = %w[GET HEAD OPTIONS].freeze
|
|
27
28
|
MAX_RETRY_AFTER = 60.0
|
|
29
|
+
# A list is never read past this many pages, so a panel that never says it has ended can't
|
|
30
|
+
# make a loop run for ever.
|
|
31
|
+
MAX_PAGES = 10_000
|
|
28
32
|
|
|
29
|
-
attr_reader :api_key, :base_url, :max_retries, :panel
|
|
33
|
+
attr_reader :api_key, :base_url, :max_retries, :panel, :allow_insecure_http
|
|
30
34
|
# How the client waits between retries and checks; replaceable in tests.
|
|
31
35
|
attr_accessor :sleeper
|
|
32
36
|
|
|
37
|
+
# base_url must be https://, or http:// to this machine; allow_insecure_http: true (or
|
|
38
|
+
# SILLYDEV_ALLOW_INSECURE_HTTP=1) allows any http:// address, sending the key in the clear.
|
|
39
|
+
# timeout: nil means the default, not no timeout.
|
|
33
40
|
def initialize(api_key = nil, base_url: nil, timeout: DEFAULT_TIMEOUT, max_retries: DEFAULT_MAX_RETRIES,
|
|
34
|
-
default_headers: {}, transport: nil)
|
|
35
|
-
key = api_key || ENV.fetch("SILLYDEV_API_KEY", nil)
|
|
41
|
+
default_headers: {}, transport: nil, allow_insecure_http: nil)
|
|
42
|
+
key = (api_key || ENV.fetch("SILLYDEV_API_KEY", nil))&.strip
|
|
36
43
|
if key.nil? || key.empty?
|
|
37
44
|
raise Error, "No API key. Pass one to SillyDev::Client.new or set the SILLYDEV_API_KEY environment " \
|
|
38
45
|
"variable. Create a key in the panel under Account, API keys."
|
|
@@ -41,10 +48,14 @@ module SillyDev
|
|
|
41
48
|
@api_key = key
|
|
42
49
|
base = base_url || ENV.fetch("SILLYDEV_BASE_URL", nil)
|
|
43
50
|
base = DEFAULT_BASE_URL if base.nil? || base.empty?
|
|
44
|
-
@base_url = base.
|
|
51
|
+
@base_url = base.sub(%r{/+\z}, "")
|
|
52
|
+
allow_insecure_http = ENV.fetch("SILLYDEV_ALLOW_INSECURE_HTTP", nil) == "1" if allow_insecure_http.nil?
|
|
53
|
+
self.class.check_base_url(@base_url, allow_insecure_http)
|
|
54
|
+
@allow_insecure_http = allow_insecure_http ? true : false
|
|
45
55
|
@max_retries = [max_retries.to_i, 0].max
|
|
46
56
|
@default_headers = default_headers.to_h
|
|
47
|
-
|
|
57
|
+
timeout ||= DEFAULT_TIMEOUT
|
|
58
|
+
@transport = transport || NetHTTPTransport.new(timeout: timeout, open_timeout: timeout)
|
|
48
59
|
@sleeper = ->(seconds) { sleep(seconds) }
|
|
49
60
|
@panel = Panel.new(self)
|
|
50
61
|
end
|
|
@@ -53,6 +64,18 @@ module SillyDev
|
|
|
53
64
|
"#<#{self.class.name} base_url=#{@base_url.inspect}>"
|
|
54
65
|
end
|
|
55
66
|
|
|
67
|
+
# Refuses a base URL that would send the API key in the clear.
|
|
68
|
+
def self.check_base_url(base_url, allow_insecure_http)
|
|
69
|
+
uri = URI.parse(base_url)
|
|
70
|
+
return if uri.scheme == "https"
|
|
71
|
+
return if uri.scheme == "http" && (allow_insecure_http || LOOPBACK.include?(uri.host))
|
|
72
|
+
|
|
73
|
+
raise Error, "The base URL #{base_url} is not https://, so the API key would be sent in the clear. Use " \
|
|
74
|
+
"https://, or pass allow_insecure_http: true (SILLYDEV_ALLOW_INSECURE_HTTP=1) if you really mean it."
|
|
75
|
+
rescue URI::InvalidURIError
|
|
76
|
+
raise Error, "The base URL #{base_url.inspect} is not a URL."
|
|
77
|
+
end
|
|
78
|
+
|
|
56
79
|
# Quotes one path parameter so that a slash or space in it cannot change the route.
|
|
57
80
|
def self.segment(value)
|
|
58
81
|
value.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |c| format("%%%02X", c.ord) }
|
|
@@ -103,6 +126,7 @@ module SillyDev
|
|
|
103
126
|
result = page(path, params.merge(page: number))
|
|
104
127
|
result.each { |item| yielder << item }
|
|
105
128
|
break unless result.next_page?
|
|
129
|
+
raise Error, "Stopped after #{MAX_PAGES} pages of #{path}: the list never ended." if result.current_page + 1 - first >= MAX_PAGES
|
|
106
130
|
|
|
107
131
|
number = result.current_page + 1
|
|
108
132
|
end
|
|
@@ -134,11 +158,14 @@ module SillyDev
|
|
|
134
158
|
end
|
|
135
159
|
|
|
136
160
|
def request_headers(extra)
|
|
137
|
-
{
|
|
138
|
-
"Authorization" => "Bearer #{@api_key}",
|
|
161
|
+
headers = {
|
|
139
162
|
"Accept" => "application/json",
|
|
140
163
|
"User-Agent" => "sillydev-ruby/#{VERSION}",
|
|
141
164
|
}.merge(@default_headers.to_h { |k, v| [k.to_s, v.to_s] }).merge(extra)
|
|
165
|
+
# The key is the client's: no other header may replace it or be sent beside it.
|
|
166
|
+
headers.reject! { |name, _| name.casecmp?("authorization") }
|
|
167
|
+
headers["Authorization"] = "Bearer #{@api_key}"
|
|
168
|
+
headers
|
|
142
169
|
end
|
|
143
170
|
|
|
144
171
|
def encode_params(params)
|
data/lib/sillydev/console.rb
CHANGED
|
@@ -838,15 +838,32 @@ module SillyDev
|
|
|
838
838
|
@credentials
|
|
839
839
|
end
|
|
840
840
|
|
|
841
|
+
# The console token (and, for sessions, the session id in each path) must not cross the
|
|
842
|
+
# network in the clear: a node address must be wss/https, unless it is this machine or
|
|
843
|
+
# allow_insecure_http was set. A panel on this machine does not make a remote node safe.
|
|
844
|
+
def check_node_url(address, secure, transport)
|
|
845
|
+
uri = URI.parse(address)
|
|
846
|
+
return if uri.scheme == secure || @client.allow_insecure_http ||
|
|
847
|
+
%w[localhost 127.0.0.1 ::1 [::1]].include?(uri.host)
|
|
848
|
+
|
|
849
|
+
raise ConsoleError.new("The node's console address #{uri.scheme}://#{uri.host} is not encrypted, so the " \
|
|
850
|
+
"console token wasn't sent.", "unavailable", transport: transport)
|
|
851
|
+
rescue URI::InvalidURIError
|
|
852
|
+
raise ConsoleError.new("The panel gave a node address that is not a URL.", "unavailable", transport: transport)
|
|
853
|
+
end
|
|
854
|
+
|
|
841
855
|
def build(kind, handlers)
|
|
842
856
|
case kind
|
|
843
857
|
when "websocket"
|
|
844
858
|
c = creds
|
|
859
|
+
check_node_url(c["socket"].to_s, "wss", kind)
|
|
845
860
|
WebsocketTransport.new(c["socket"].to_s, @origin, c["token"].to_s, handlers)
|
|
846
861
|
when "stream", "poll"
|
|
847
862
|
c = creds
|
|
848
863
|
raise ConsoleError.new("The panel did not give a sessions address.", "unavailable", transport: kind) if c["sessions"].to_s.empty?
|
|
849
864
|
|
|
865
|
+
check_node_url(c["sessions"].to_s, "https", kind)
|
|
866
|
+
|
|
850
867
|
SessionTransport.new(kind, c["sessions"].to_s, c["token"].to_s, handlers, @poll_wait, @timings)
|
|
851
868
|
when "relay"
|
|
852
869
|
RelayTransport.new(@client, @server, handlers, @relay_interval)
|
data/lib/sillydev/errors.rb
CHANGED
|
@@ -72,11 +72,13 @@ module SillyDev
|
|
|
72
72
|
# A wait such as servers.wait_for_state ran out of time. #state is the server's state when it
|
|
73
73
|
# gave up.
|
|
74
74
|
class WaitTimeoutError < Error
|
|
75
|
-
|
|
75
|
+
# last_error is the error of the last check, when the last check failed.
|
|
76
|
+
attr_reader :state, :last_error
|
|
76
77
|
|
|
77
|
-
def initialize(message = nil, state: nil)
|
|
78
|
+
def initialize(message = nil, state: nil, last_error: nil)
|
|
78
79
|
super(message)
|
|
79
80
|
@state = state
|
|
81
|
+
@last_error = last_error
|
|
80
82
|
end
|
|
81
83
|
end
|
|
82
84
|
|
|
@@ -114,15 +116,33 @@ module SillyDev
|
|
|
114
116
|
module_function
|
|
115
117
|
|
|
116
118
|
# Seconds from a Retry-After header, or nil when it is missing or not a number.
|
|
119
|
+
# Seconds to wait, from Retry-After as seconds or as an HTTP date.
|
|
117
120
|
def parse_retry_after(value)
|
|
118
121
|
return nil if value.nil?
|
|
119
122
|
|
|
120
|
-
|
|
123
|
+
text = value.to_s.strip
|
|
124
|
+
seconds = Float(text, exception: false) || http_date_seconds(text)
|
|
125
|
+
return nil if seconds.nil? || seconds.nan? || seconds.infinite?
|
|
126
|
+
|
|
121
127
|
seconds.negative? ? 0.0 : seconds
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def http_date_seconds(text)
|
|
131
|
+
require "time"
|
|
132
|
+
Time.httpdate(text) - Time.now
|
|
122
133
|
rescue ArgumentError
|
|
123
134
|
nil
|
|
124
135
|
end
|
|
125
136
|
|
|
137
|
+
# The usual words for a status, for an error answer with no message of its own.
|
|
138
|
+
REASONS = {
|
|
139
|
+
400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found",
|
|
140
|
+
405 => "Method Not Allowed", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone",
|
|
141
|
+
413 => "Payload Too Large", 415 => "Unsupported Media Type", 422 => "Unprocessable Content",
|
|
142
|
+
429 => "Too Many Requests", 500 => "Internal Server Error", 502 => "Bad Gateway",
|
|
143
|
+
503 => "Service Unavailable", 504 => "Gateway Timeout"
|
|
144
|
+
}.freeze
|
|
145
|
+
|
|
126
146
|
# The exception that matches an error response.
|
|
127
147
|
def for_response(response)
|
|
128
148
|
status = response.status
|
|
@@ -147,7 +167,7 @@ module SillyDev
|
|
|
147
167
|
end
|
|
148
168
|
end
|
|
149
169
|
message = errors.empty? ? "" : (errors.first["detail"] || errors.first["code"]).to_s
|
|
150
|
-
message = "HTTP error" if message.empty?
|
|
170
|
+
message = REASONS.fetch(status, "HTTP error") if message.empty?
|
|
151
171
|
message = "#{status}: #{message}"
|
|
152
172
|
|
|
153
173
|
kwargs = { status_code: status, errors: errors, response: response }
|
data/lib/sillydev/mcp_server.rb
CHANGED
|
@@ -11,8 +11,15 @@ module SillyDev
|
|
|
11
11
|
# you want the assistant to have.
|
|
12
12
|
#
|
|
13
13
|
# The tools are deliberately few: list servers, read a server's status, power actions, console
|
|
14
|
-
# commands, reading recent console output, list and read files, Git deploys
|
|
15
|
-
#
|
|
14
|
+
# commands, reading recent console output, list and read files, Git deploys, listing backups,
|
|
15
|
+
# checking the bucket backups are copied to (its keys can only be set through the API or the CLI,
|
|
16
|
+
# never here), reading a server's crash and disk alerts and sending a test alert, listing databases and
|
|
17
|
+
# reading a Redis store's keys, plus reading and changing the account's status page notifications
|
|
18
|
+
# (emails and Discord webhooks; changing them needs a key with the status.write scope).
|
|
19
|
+
# None spends money, deletes a server or a backup, or changes who can reach a server. Power
|
|
20
|
+
# actions (kill included), console commands and Git deploys do change a live server and run
|
|
21
|
+
# without a confirmation step of their own, so give the key only the permissions you want the
|
|
22
|
+
# assistant to have: a key without them can't use those tools.
|
|
16
23
|
class MCPServer
|
|
17
24
|
PROTOCOL_VERSIONS = %w[2025-06-18 2025-03-26 2024-11-05].freeze
|
|
18
25
|
|
|
@@ -21,14 +28,30 @@ module SillyDev
|
|
|
21
28
|
|
|
22
29
|
INSTRUCTIONS = "Tools for the user's Silly Development servers (Discord bots and other apps). " \
|
|
23
30
|
"Servers are named by their 8-character identifier, which list_servers returns. " \
|
|
24
|
-
"Power actions and console commands affect a live server: say what you are about to do first."
|
|
31
|
+
"Power actions and console commands affect a live server: say what you are about to do first. " \
|
|
32
|
+
"Databases and Redis stores are named by their numeric id, which list_databases returns."
|
|
25
33
|
|
|
26
34
|
SERVER = { "server" => { "type" => "string", "description" => "The server's 8-character identifier or UUID." } }.freeze
|
|
27
35
|
|
|
36
|
+
DATABASE = {
|
|
37
|
+
"database" => { "type" => "integer", "description" => "The database's numeric id from list_databases." },
|
|
38
|
+
}.freeze
|
|
39
|
+
|
|
40
|
+
# restore_database_backup's answer until the user has agreed, the same in every SDK.
|
|
41
|
+
RESTORE_CONFIRM = "Restoring replaces everything in the database with the backup. " \
|
|
42
|
+
"Ask the user to confirm, then call again with confirm: true."
|
|
43
|
+
|
|
44
|
+
RESTORE_INPUT = DATABASE.merge(
|
|
45
|
+
"backup" => { "type" => "string", "description" => "The backup's id, from list_database_backups." },
|
|
46
|
+
"confirm" => { "type" => "boolean", "description" => "Must be true: the user has agreed to replace the database." }
|
|
47
|
+
).freeze
|
|
48
|
+
|
|
28
49
|
def self.schema(properties = {}, required = [])
|
|
29
50
|
{ "type" => "object", "properties" => properties, "required" => required }
|
|
30
51
|
end
|
|
31
52
|
|
|
53
|
+
STATUS_PRESETS = %w[everything new_resolved major].freeze
|
|
54
|
+
|
|
32
55
|
TOOLS = [
|
|
33
56
|
["list_servers", "List the servers this API key can reach, with their identifiers, names and limits.", schema],
|
|
34
57
|
["server_status",
|
|
@@ -44,12 +67,99 @@ module SillyDev
|
|
|
44
67
|
schema(SERVER.merge("lines" => { "type" => "integer", "default" => 100 }), ["server"])],
|
|
45
68
|
["list_files", "List the files and folders in one directory of a server. directory defaults to /.",
|
|
46
69
|
schema(SERVER.merge("directory" => { "type" => "string", "default" => "/" }), ["server"])],
|
|
47
|
-
["read_file",
|
|
70
|
+
["read_file",
|
|
71
|
+
"Read a text file from a server, such as a config file or a log. The contents go to the model as they " \
|
|
72
|
+
"are, so a file such as .env may hold secrets.",
|
|
48
73
|
schema(SERVER.merge("path" => { "type" => "string" }), %w[server path])],
|
|
49
|
-
["git_deploy",
|
|
50
|
-
|
|
74
|
+
["git_deploy",
|
|
75
|
+
"Deploy the Git repository linked to a server now. Returns the queued deployment. Set resume to turn " \
|
|
76
|
+
"auto deploy back on after a rollback as well.",
|
|
77
|
+
schema(SERVER.merge("resume" => { "type" => "boolean", "default" => false }), ["server"])],
|
|
78
|
+
["git_rollback",
|
|
79
|
+
"Deploy an earlier commit of a server's linked repository again: the previous good deployment, or the one " \
|
|
80
|
+
"named by its UUID. Auto deploy pauses until git_deploy is called with resume.",
|
|
81
|
+
schema(SERVER.merge("deployment" => { "type" => "string" }), ["server"])],
|
|
82
|
+
["git_deployment_log",
|
|
83
|
+
"Read why a Git deployment failed: its status, error and what its build step and release command printed. " \
|
|
84
|
+
"The newest deployment unless one is named by its UUID. The output goes to the model as it is and may echo secrets.",
|
|
85
|
+
schema(SERVER.merge("deployment" => { "type" => "string" }), ["server"])],
|
|
51
86
|
["list_backups", "List a server's backups: name, size, whether it finished and succeeded, and when.",
|
|
52
87
|
schema(SERVER, ["server"])],
|
|
88
|
+
["get_status_subscription",
|
|
89
|
+
"Get whether the account is emailed about incidents posted on the status page, which emails (the preset), " \
|
|
90
|
+
"and the Discord webhooks it added (their ids and the last characters of their address). Only incidents " \
|
|
91
|
+
"staff post by hand are sent.",
|
|
92
|
+
schema],
|
|
93
|
+
["set_status_email_subscription",
|
|
94
|
+
"Turn emails about status page incidents on or off for the account's own email address, and choose which: " \
|
|
95
|
+
"\"everything\" (new incidents, every update and the resolution), \"new_resolved\" (only the start and the " \
|
|
96
|
+
"resolution) or \"major\" (everything, but only for partial and major outages).",
|
|
97
|
+
schema({ "subscribed" => { "type" => "boolean", "description" => "True to get the emails, false to stop." },
|
|
98
|
+
"preset" => { "type" => "string", "enum" => STATUS_PRESETS,
|
|
99
|
+
"description" => "Which emails. Optional; it keeps the current choice." } },
|
|
100
|
+
["subscribed"])],
|
|
101
|
+
["add_status_discord_webhook",
|
|
102
|
+
"Send status page incidents to a Discord channel through its webhook URL (https://discord.com/api/webhooks/...). " \
|
|
103
|
+
"A test message is sent first and the webhook is only kept if it arrives. At most five per account. Only add " \
|
|
104
|
+
"a webhook the account's owner gave you.",
|
|
105
|
+
schema({ "url" => { "type" => "string", "maxLength" => 300, "description" => "The Discord webhook URL." },
|
|
106
|
+
"label" => { "type" => "string", "maxLength" => 64, "description" => "A name for it. Optional." },
|
|
107
|
+
"preset" => { "type" => "string", "enum" => STATUS_PRESETS,
|
|
108
|
+
"description" => "Which messages. Optional; defaults to everything." } },
|
|
109
|
+
["url"])],
|
|
110
|
+
["remove_status_discord_webhook",
|
|
111
|
+
"Stop sending status page incidents to one of the account's Discord webhooks. Its id is in " \
|
|
112
|
+
"get_status_subscription.",
|
|
113
|
+
schema({ "id" => { "type" => "integer", "minimum" => 1, "description" => "The webhook's id." } }, ["id"])],
|
|
114
|
+
["list_databases",
|
|
115
|
+
"List the account's databases and Redis (Valkey) stores: id, name, engine, version, address and size. " \
|
|
116
|
+
"Passwords are left out.", schema],
|
|
117
|
+
["list_store_keys",
|
|
118
|
+
"List keys in a Redis (Valkey) store, by its database id, matching a glob pattern such as user:*. " \
|
|
119
|
+
"Returns up to 500 keys with their type and milliseconds left to live (-1 for never).",
|
|
120
|
+
schema(DATABASE.merge("pattern" => { "type" => "string", "default" => "*" }), ["database"])],
|
|
121
|
+
["read_store_key",
|
|
122
|
+
"Read one key of a Redis (Valkey) store: its type, expiry and value (or first items). The value goes " \
|
|
123
|
+
"to the model as it is, so it may be a token or other secret.",
|
|
124
|
+
schema(DATABASE.merge("key" => { "type" => "string" }), %w[database key])],
|
|
125
|
+
["server_alerts",
|
|
126
|
+
"Get which alerts a server sends when it crashes, keeps crashing, runs out of memory or fills its disk, where " \
|
|
127
|
+
"they go (email, a Discord or custom webhook), and the webhook's last deliveries.",
|
|
128
|
+
schema(SERVER, ["server"])],
|
|
129
|
+
["send_test_alert", "Send a test alert for a server to its email and webhook, to check they arrive.",
|
|
130
|
+
schema(SERVER, ["server"])],
|
|
131
|
+
["backup_destination",
|
|
132
|
+
"Whether copying a server's backups to the owner's own S3 bucket is available, and the bucket set up for it " \
|
|
133
|
+
"(never its keys).", schema(SERVER, ["server"])],
|
|
134
|
+
["test_backup_destination",
|
|
135
|
+
"Write, read and delete a small test file in the server's own backup bucket, to check it works.",
|
|
136
|
+
schema(SERVER, ["server"])],
|
|
137
|
+
["copy_backup_to_own_storage",
|
|
138
|
+
"Copy a finished backup that is not in the owner's own S3 bucket yet to it, in the background. Needs the " \
|
|
139
|
+
"bucket set up and copying switched on.",
|
|
140
|
+
schema(SERVER.merge("backup" => { "type" => "string" }), %w[server backup])],
|
|
141
|
+
["list_folders",
|
|
142
|
+
"List the user's dashboard folders and which server (by UUID) is in which. Fails with not found while the " \
|
|
143
|
+
"panel has folders switched off.", schema],
|
|
144
|
+
["list_sessions",
|
|
145
|
+
"List the browsers signed in to the account, most recently active first, with their browser, system, IP " \
|
|
146
|
+
"address and when they were last active. Signing one out is done in the panel.", schema],
|
|
147
|
+
["bulk_action",
|
|
148
|
+
"Start, stop, restart, kill or back up several servers at once (up to 25, by UUID). Returns what happened " \
|
|
149
|
+
"to each. Affects live servers: say what you are about to do first.",
|
|
150
|
+
schema({ "action" => { "type" => "string", "enum" => %w[start stop restart kill backup] },
|
|
151
|
+
"servers" => { "type" => "array", "items" => { "type" => "string" }, "description" => "Server UUIDs." } },
|
|
152
|
+
%w[action servers])],
|
|
153
|
+
["list_database_backups",
|
|
154
|
+
"List a database's backups (newest first) and how its daily backups are going. Databases are named by " \
|
|
155
|
+
"their numeric id.",
|
|
156
|
+
schema(DATABASE, ["database"])],
|
|
157
|
+
["backup_database", "Back a database up now. Only a few are allowed a day.", schema(DATABASE, ["database"])],
|
|
158
|
+
["restore_database_backup",
|
|
159
|
+
"Replace everything in a database with one of its backups. The database is offline for a few seconds and " \
|
|
160
|
+
"anything written since the backup is lost, though the restore can be undone from the Databases page for a " \
|
|
161
|
+
"few days. Ask the user first, then call again with confirm: true.",
|
|
162
|
+
schema(RESTORE_INPUT, %w[database backup confirm])],
|
|
53
163
|
].map { |name, description, input| { "name" => name, "description" => description, "inputSchema" => input } }.freeze
|
|
54
164
|
|
|
55
165
|
TOOL_NAMES = TOOLS.map { |tool| tool["name"] }.freeze
|
|
@@ -88,6 +198,9 @@ module SillyDev
|
|
|
88
198
|
handle(message)
|
|
89
199
|
rescue JSON::ParserError
|
|
90
200
|
error_reply(nil, -32_700, "Parse error")
|
|
201
|
+
rescue StandardError => e
|
|
202
|
+
# Nothing a client sends may stop the server: it answers and keeps serving.
|
|
203
|
+
error_reply(nil, -32_603, "Internal error: #{e.class}")
|
|
91
204
|
end
|
|
92
205
|
|
|
93
206
|
def handle(message)
|
|
@@ -95,8 +208,11 @@ module SillyDev
|
|
|
95
208
|
|
|
96
209
|
id = message["id"]
|
|
97
210
|
method = message["method"]
|
|
98
|
-
return
|
|
211
|
+
return error_reply(id, -32_600, "Invalid Request") unless method.is_a?(String)
|
|
212
|
+
return nil if !message.key?("id") && method.start_with?("notifications/")
|
|
99
213
|
return nil unless message.key?("id")
|
|
214
|
+
return error_reply(id, -32_600, "Invalid Request: params must be an object") unless
|
|
215
|
+
message["params"].nil? || message["params"].is_a?(Hash)
|
|
100
216
|
|
|
101
217
|
result = case method
|
|
102
218
|
when "initialize" then initialize_result(message["params"] || {})
|
|
@@ -108,6 +224,8 @@ module SillyDev
|
|
|
108
224
|
{ "jsonrpc" => "2.0", "id" => id, "result" => result }
|
|
109
225
|
rescue ArgumentError => e
|
|
110
226
|
error_reply(id, -32_602, e.message)
|
|
227
|
+
rescue StandardError => e
|
|
228
|
+
error_reply(id, -32_603, "Internal error: #{e.class}")
|
|
111
229
|
end
|
|
112
230
|
|
|
113
231
|
# Runs one tool. Errors from the API come back as a tool result with isError, so the
|
|
@@ -173,17 +291,144 @@ module SillyDev
|
|
|
173
291
|
return text if text.length <= MAX_FILE_CHARS
|
|
174
292
|
|
|
175
293
|
"#{text[-MAX_FILE_CHARS..]}\n[showing the last #{MAX_FILE_CHARS} characters of #{text.length}]"
|
|
176
|
-
when "git_deploy" then
|
|
294
|
+
when "git_deploy" then git_deploy(arg(args, "server"), args["resume"] == true)
|
|
295
|
+
when "git_rollback" then git_rollback(arg(args, "server"), args["deployment"])
|
|
296
|
+
when "git_deployment_log" then git_deployment_log(arg(args, "server"), args["deployment"])
|
|
177
297
|
when "list_backups" then panel.backups.list(arg(args, "server")).to_a
|
|
298
|
+
when "get_status_subscription" then panel.account.get_status_subscription
|
|
299
|
+
when "set_status_email_subscription" then set_status_email(args)
|
|
300
|
+
when "add_status_discord_webhook"
|
|
301
|
+
panel.account.add_status_discord_webhook(url: arg(args, "url"), label: optional_string(args, "label"),
|
|
302
|
+
preset: status_preset(args))
|
|
303
|
+
when "remove_status_discord_webhook"
|
|
304
|
+
id = args["id"]
|
|
305
|
+
raise ToolError, "id must be a whole number." unless id.is_a?(Integer) && id >= 1
|
|
306
|
+
|
|
307
|
+
panel.account.remove_status_discord_webhook(id)
|
|
308
|
+
{ "removed" => true }
|
|
309
|
+
when "list_databases"
|
|
310
|
+
keys = %w[id label engine host port username size_bytes quota_bytes status]
|
|
311
|
+
(panel.databases.list["databases"] || []).map { |d| d.slice(*keys).merge("version" => (d["version"] || {})["name"]) }
|
|
312
|
+
when "list_store_keys" then list_store_keys(database_id(args), (args["pattern"] || "*").to_s)
|
|
313
|
+
when "read_store_key" then panel.databases.get_key(database_id(args), arg(args, "key"))
|
|
314
|
+
when "server_alerts" then server_alerts(arg(args, "server"))
|
|
315
|
+
when "send_test_alert"
|
|
316
|
+
panel.settings.send_test_alert(arg(args, "server"))
|
|
317
|
+
"A test alert for #{arg(args, 'server')} is on its way."
|
|
318
|
+
when "backup_destination" then panel.backups.destination(arg(args, "server"))
|
|
319
|
+
when "test_backup_destination" then panel.backups.test_destination(arg(args, "server"))
|
|
320
|
+
when "copy_backup_to_own_storage" then panel.backups.retry_copy(arg(args, "server"), arg(args, "backup"))
|
|
321
|
+
when "list_database_backups" then panel.databases.backups(database_id(args))
|
|
322
|
+
when "backup_database" then panel.databases.back_up(database_id(args))
|
|
323
|
+
when "restore_database_backup"
|
|
324
|
+
raise ToolError, RESTORE_CONFIRM unless args["confirm"] == true
|
|
325
|
+
|
|
326
|
+
panel.databases.restore_backup(database_id(args), arg(args, "backup"))
|
|
327
|
+
when "list_folders" then panel.folders.list
|
|
328
|
+
when "list_sessions" then panel.account.sessions
|
|
329
|
+
when "bulk_action" then bulk_action(args)
|
|
178
330
|
end
|
|
179
331
|
end
|
|
180
332
|
|
|
333
|
+
def set_status_email(args)
|
|
334
|
+
subscribed = args["subscribed"]
|
|
335
|
+
raise ToolError, "subscribed must be true or false." unless [true, false].include?(subscribed)
|
|
336
|
+
|
|
337
|
+
@client.panel.account.update_status_subscription(subscribed: subscribed, preset: status_preset(args))
|
|
338
|
+
end
|
|
339
|
+
|
|
340
|
+
def optional_string(args, name)
|
|
341
|
+
value = args[name]
|
|
342
|
+
value&.to_s
|
|
343
|
+
end
|
|
344
|
+
|
|
345
|
+
def status_preset(args)
|
|
346
|
+
preset = optional_string(args, "preset")
|
|
347
|
+
return preset if preset.nil? || STATUS_PRESETS.include?(preset)
|
|
348
|
+
|
|
349
|
+
raise ToolError, "preset must be everything, new_resolved or major."
|
|
350
|
+
end
|
|
351
|
+
|
|
352
|
+
def list_store_keys(database, pattern)
|
|
353
|
+
found = []
|
|
354
|
+
cursor = "0"
|
|
355
|
+
loop do
|
|
356
|
+
page = @client.panel.databases.list_keys(database, pattern: pattern, cursor: cursor, count: 500)
|
|
357
|
+
found.concat((page["keys"] || []).map { |k| k.slice("key", "type", "ttl_ms") })
|
|
358
|
+
cursor = page["cursor"].to_s
|
|
359
|
+
break if cursor == "0" || cursor.empty? || found.length >= 500
|
|
360
|
+
end
|
|
361
|
+
{ "keys" => found.first(500), "complete" => (cursor == "0" || cursor.empty?) && found.length <= 500 }
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
def server_alerts(server)
|
|
365
|
+
settings = @client.panel.settings.alerts(server).dup
|
|
366
|
+
settings["webhook"] = (settings["webhook"] || {}).except("secret")
|
|
367
|
+
settings["recent_deliveries"] = @client.panel.settings.alert_deliveries(server)
|
|
368
|
+
settings
|
|
369
|
+
end
|
|
370
|
+
|
|
371
|
+
def database_id(args)
|
|
372
|
+
value = Integer(args["database"], exception: false)
|
|
373
|
+
raise ToolError, "database is required: its numeric id" if value.nil? || value <= 0
|
|
374
|
+
|
|
375
|
+
value
|
|
376
|
+
end
|
|
377
|
+
|
|
378
|
+
def git_deploy(server, resume)
|
|
379
|
+
return @client.panel.git.resume(server, deploy: true)["deployment"] if resume
|
|
380
|
+
|
|
381
|
+
@client.panel.git.deploy(server)
|
|
382
|
+
end
|
|
383
|
+
|
|
384
|
+
def git_rollback(server, deployment)
|
|
385
|
+
if deployment.nil? || deployment.to_s.empty?
|
|
386
|
+
previous = @client.panel.git.get(server)["previous"]
|
|
387
|
+
raise ToolError, "There is no earlier deployment to roll back to." unless previous
|
|
388
|
+
|
|
389
|
+
deployment = previous["uuid"]
|
|
390
|
+
end
|
|
391
|
+
@client.panel.git.redeploy(server, deployment.to_s)
|
|
392
|
+
end
|
|
393
|
+
|
|
394
|
+
def git_deployment_log(server, deployment)
|
|
395
|
+
if deployment.nil? || deployment.to_s.empty?
|
|
396
|
+
deployments = @client.panel.git.get(server)["deployments"] || []
|
|
397
|
+
return "#{server} has no deployments yet." if deployments.empty?
|
|
398
|
+
|
|
399
|
+
deployment = deployments.first["uuid"]
|
|
400
|
+
end
|
|
401
|
+
@client.panel.git.deployment(server, deployment.to_s)
|
|
402
|
+
end
|
|
403
|
+
|
|
404
|
+
def bulk_action(args)
|
|
405
|
+
action = arg(args, "action")
|
|
406
|
+
raise ArgumentError, "action must be start, stop, restart, kill or backup" unless %w[start stop restart kill backup].include?(action)
|
|
407
|
+
|
|
408
|
+
servers = args["servers"]
|
|
409
|
+
raise ArgumentError, "servers must be a list of server UUIDs" unless servers.is_a?(Array) && servers.all?(String)
|
|
410
|
+
|
|
411
|
+
@client.panel.folders.bulk(action, servers)
|
|
412
|
+
end
|
|
413
|
+
|
|
181
414
|
def read_console(server, lines)
|
|
182
415
|
history = @client.panel.console.history(server)
|
|
183
416
|
return "#{server} has no console output: it is offline, or has printed nothing since it started." if history.empty?
|
|
184
417
|
|
|
185
|
-
|
|
186
|
-
|
|
418
|
+
text = history.last(self.class.line_count(lines)).join("\n")
|
|
419
|
+
return text if text.length <= MAX_FILE_CHARS
|
|
420
|
+
|
|
421
|
+
"#{text[-MAX_FILE_CHARS..]}\n[showing the last #{MAX_FILE_CHARS} characters of #{text.length}]"
|
|
422
|
+
end
|
|
423
|
+
|
|
424
|
+
# read_console's lines, the same in every SDK: a number (or a numeric string) rounded down and
|
|
425
|
+
# at least 1; anything else, or nothing, is 100.
|
|
426
|
+
def self.line_count(value) # rubocop:disable Lint/IneffectiveAccessModifier
|
|
427
|
+
n = case value
|
|
428
|
+
when Numeric then value.to_f
|
|
429
|
+
when String then value.strip.empty? ? nil : Float(value, exception: false)
|
|
430
|
+
end
|
|
431
|
+
n.nil? || !n.finite? ? 100 : [n.floor, 1].max
|
|
187
432
|
end
|
|
188
433
|
|
|
189
434
|
def error_reply(id, code, message)
|
|
@@ -45,11 +45,29 @@ module SillyDev
|
|
|
45
45
|
"#{engine} #{version}"
|
|
46
46
|
end
|
|
47
47
|
|
|
48
|
+
LOOPBACK = %w[localhost 127.0.0.1 ::1 [::1]].freeze
|
|
49
|
+
|
|
50
|
+
# Whether the key may be sent to the endpoint: https is, and so is http to this machine; any
|
|
51
|
+
# other http endpoint needs SILLYDEV_ALLOW_INSECURE_HTTP=1.
|
|
52
|
+
def self.endpoint_safe?(endpoint)
|
|
53
|
+
uri = URI.parse(endpoint)
|
|
54
|
+
return true if uri.scheme == "https"
|
|
55
|
+
|
|
56
|
+
uri.scheme == "http" && (LOOPBACK.include?(uri.host) || ENV.fetch("SILLYDEV_ALLOW_INSECURE_HTTP", nil) == "1")
|
|
57
|
+
rescue URI::InvalidURIError
|
|
58
|
+
false
|
|
59
|
+
end
|
|
60
|
+
|
|
48
61
|
def initialize(key = nil, endpoint: nil, service: nil, environment: nil, release: nil, runtime_metrics: true,
|
|
49
62
|
capture_unhandled: true, sample_rate: 1.0, before_send: nil, flush_interval: 10.0,
|
|
50
63
|
max_buffer_bytes: 1_000_000, slow_threshold_ms: 1000, logger: nil, debug: false, active: true)
|
|
51
|
-
@key = key
|
|
64
|
+
@key = key.to_s.strip.empty? ? nil : key.to_s.strip
|
|
52
65
|
@endpoint = endpoint.to_s.chomp("/")
|
|
66
|
+
unless @endpoint.empty? || self.class.endpoint_safe?(@endpoint)
|
|
67
|
+
warn "sillydev.monitoring: the endpoint is not https://, so the key would be sent in the clear; " \
|
|
68
|
+
"monitoring is off (set SILLYDEV_ALLOW_INSECURE_HTTP=1 to allow it)"
|
|
69
|
+
@endpoint = ""
|
|
70
|
+
end
|
|
53
71
|
@service = (service || "default").to_s.downcase[0, 64]
|
|
54
72
|
@environment = (environment || "production").to_s.downcase[0, 64]
|
|
55
73
|
@release = release ? release.to_s[0, 64] : nil
|
|
@@ -63,7 +81,7 @@ module SillyDev
|
|
|
63
81
|
@logger = logger
|
|
64
82
|
@debug = debug
|
|
65
83
|
@instance = SecureRandom.hex(4)
|
|
66
|
-
@active = active && key && !@endpoint.empty? ? true : false
|
|
84
|
+
@active = active && @key && !@endpoint.empty? ? true : false
|
|
67
85
|
|
|
68
86
|
# Replaceable in tests.
|
|
69
87
|
@clock = -> { Time.now.to_f }
|
|
@@ -208,7 +226,9 @@ module SillyDev
|
|
|
208
226
|
next unless enabled?
|
|
209
227
|
|
|
210
228
|
duration = finite(duration_ms)
|
|
211
|
-
|
|
229
|
+
# Below the threshold isn't slow (as in the JS and Python SDKs), and would use up the
|
|
230
|
+
# day's slow operations.
|
|
231
|
+
next if duration.nil? || duration < @slow_threshold_ms
|
|
212
232
|
|
|
213
233
|
item = {
|
|
214
234
|
"ts" => @clock.call,
|
|
@@ -35,11 +35,11 @@ module SillyDev
|
|
|
35
35
|
collections = [count - @gc_count, 0].max
|
|
36
36
|
samples << ["runtime.gc.count", "counter", collections.to_f]
|
|
37
37
|
time = gc_time
|
|
38
|
-
if time && @gc_time
|
|
39
|
-
# Ruby keeps the total time spent in GC, not each pause
|
|
40
|
-
#
|
|
41
|
-
|
|
42
|
-
|
|
38
|
+
if time && @gc_time
|
|
39
|
+
# Ruby keeps only the total time spent in GC, not each pause, so that is what is sent:
|
|
40
|
+
# a made-up pause histogram would show the window's average as its min, max and every
|
|
41
|
+
# percentile.
|
|
42
|
+
samples << ["runtime.gc.time", "counter", [(time - @gc_time).to_f, 0.0].max]
|
|
43
43
|
end
|
|
44
44
|
@gc_count = count
|
|
45
45
|
@gc_time = time
|
data/lib/sillydev/monitoring.rb
CHANGED
|
@@ -19,6 +19,10 @@ module SillyDev
|
|
|
19
19
|
# this file. Docs: https://sillydev.co.uk/docs/monitoring
|
|
20
20
|
module Monitoring
|
|
21
21
|
KEY_RE = /\Asdevm_([1-9][0-9]*)_/
|
|
22
|
+
WRONG_KINDS = {
|
|
23
|
+
"sdevb_" => "a browser key (sdevb_) cannot be used here",
|
|
24
|
+
"sdevn_" => "a Wings node token cannot be used here",
|
|
25
|
+
}.freeze
|
|
22
26
|
|
|
23
27
|
@current = nil
|
|
24
28
|
@init_lock = Mutex.new
|
|
@@ -51,10 +55,16 @@ module SillyDev
|
|
|
51
55
|
@current = nil
|
|
52
56
|
previous&.shutdown(2.0)
|
|
53
57
|
|
|
54
|
-
key
|
|
58
|
+
key = key.to_s.strip
|
|
59
|
+
key = env("SILLYDEV_MONITORING_KEY").to_s.strip if key.empty?
|
|
60
|
+
key = nil if key.empty?
|
|
55
61
|
disabled = %w[1 true yes on].include?(env("SILLYDEV_MONITORING_DISABLED").to_s.downcase)
|
|
56
62
|
endpoint ||= env("SILLYDEV_MONITORING_URL")
|
|
57
63
|
active = enabled && !disabled && key ? true : false
|
|
64
|
+
if active && WRONG_KINDS.key?(key[0, 6])
|
|
65
|
+
warn "sillydev.monitoring: #{WRONG_KINDS[key[0, 6]]}; use a server key (sdevm_). Monitoring is off."
|
|
66
|
+
active = false
|
|
67
|
+
end
|
|
58
68
|
if active && endpoint.nil?
|
|
59
69
|
endpoint = endpoint_for_key(key)
|
|
60
70
|
if endpoint.nil?
|