@uknows/setup 0.0.0-stage → 0.1.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.
- package/LICENSE +190 -0
- package/README.md +142 -2
- package/bin/uknows-setup.mjs +14 -0
- package/lib/check.mjs +211 -0
- package/lib/cli.mjs +166 -0
- package/lib/contract-docs.mjs +1154 -0
- package/lib/contract.mjs +66 -0
- package/lib/detect.mjs +575 -0
- package/lib/diff.mjs +147 -0
- package/lib/doc.mjs +98 -0
- package/lib/dockerfile.mjs +372 -0
- package/lib/endpoint.mjs +50 -0
- package/lib/engine.mjs +607 -0
- package/lib/existing.mjs +168 -0
- package/lib/git.mjs +47 -0
- package/lib/hosts.mjs +145 -0
- package/lib/manifest.mjs +112 -0
- package/lib/settings.mjs +280 -0
- package/lib/stacks/dotnet.mjs +165 -0
- package/lib/stacks/guided.mjs +104 -0
- package/lib/stacks/index.mjs +10 -0
- package/lib/stacks/java.mjs +56 -0
- package/lib/stacks/k8s.mjs +31 -0
- package/lib/stacks/node.mjs +235 -0
- package/lib/stacks/otel.mjs +11 -0
- package/lib/stacks/python-bootstrap.mjs +51 -0
- package/lib/stacks/python.mjs +434 -0
- package/lib/types.mjs +161 -0
- package/lib/ui.mjs +106 -0
- package/lib/workspace.mjs +198 -0
- package/package.json +42 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 the UKNOWS authors
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,143 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @uknows/setup
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Add standard OpenTelemetry to your app, so it sends traces to UKNOWS.
|
|
4
|
+
|
|
5
|
+
Run it in the root folder of your repo:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx @uknows/setup
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
1. It finds each service in your repo: its language, its framework, its Dockerfile or start command, and where it runs.
|
|
12
|
+
2. It shows the plan: the diff of every file it will change and the packages it will add. Nothing changes yet.
|
|
13
|
+
3. You approve once. Press Enter, or type n to stop.
|
|
14
|
+
4. It makes the change with your own files and your own package manager.
|
|
15
|
+
5. It asks for your key and checks it: UKNOWS says which workspace and environment the key sends to, and the tool sends 1 test span. The key does not show on the screen and the tool never writes it to a file.
|
|
16
|
+
|
|
17
|
+
Then commit, open a pull request and deploy as usual. `npx @uknows/setup remove` undoes the change.
|
|
18
|
+
|
|
19
|
+
Full docs: https://uknows.defacloud.my/docs
|
|
20
|
+
|
|
21
|
+
## What it supports
|
|
22
|
+
|
|
23
|
+
| Stack | What setup does |
|
|
24
|
+
|---|---|
|
|
25
|
+
| Node.js (CommonJS and ES modules) | Adds the OpenTelemetry packages with npm, pnpm or yarn, loads them with `NODE_OPTIONS`, adds the 5 settings. |
|
|
26
|
+
| Python | Adds the packages to `requirements.txt` or `pyproject.toml`, starts the app with `opentelemetry-instrument`, adds the 5 settings. |
|
|
27
|
+
| Java | Adds the pinned OpenTelemetry Java agent to the Dockerfile (Docker checks its checksum), loads it with `JAVA_TOOL_OPTIONS`, adds the 5 settings. |
|
|
28
|
+
| .NET | Adds `OpenTelemetry.AutoInstrumentation` to the project file, starts the app with `instrument.sh`, adds the 5 settings. |
|
|
29
|
+
| Go, PHP, Ruby | Adds the 5 settings, then prints the code steps for you to do. |
|
|
30
|
+
| Already uses OpenTelemetry | Adds only the settings. Keeps a Collector address and shows what to change. |
|
|
31
|
+
|
|
32
|
+
| Where it runs | Found from |
|
|
33
|
+
|---|---|
|
|
34
|
+
| Docker and VMs (Amazon EC2, Azure VMs, Alibaba ECS and others) | Dockerfile, Compose, systemd, cloud-init, Alibaba ECS in Terraform |
|
|
35
|
+
| Kubernetes (AKS, EKS, GKE, Alibaba ACK) | Kubernetes manifests, Helm charts, kubectl and helm deploy steps, Alibaba ACK in Terraform |
|
|
36
|
+
| Azure Container Apps | Terraform, Bicep, `az containerapp`, the deploy action, `azure.yaml` |
|
|
37
|
+
| Azure App Service | Terraform, Bicep, `az webapp`, the deploy action, `azure.yaml` |
|
|
38
|
+
| AWS ECS and Fargate | Terraform, CloudFormation, task definition files, `aws ecs`, the deploy action, Copilot |
|
|
39
|
+
| Alibaba SAE | Terraform, `aliyun sae`, SAE addresses |
|
|
40
|
+
|
|
41
|
+
For each place it finds, it prints the steps to set your key once as a secret there.
|
|
42
|
+
|
|
43
|
+
## What it changes
|
|
44
|
+
|
|
45
|
+
- **Packages.** It adds the upstream OpenTelemetry packages for your stack:
|
|
46
|
+
- Node.js: `@opentelemetry/api` and `@opentelemetry/auto-instrumentations-node`, with npm, pnpm or yarn.
|
|
47
|
+
- Python: `opentelemetry-distro`, the OTLP exporter and the packages for your libraries, in your requirements file or `pyproject.toml`.
|
|
48
|
+
- .NET: `OpenTelemetry.AutoInstrumentation` in your project file.
|
|
49
|
+
- Java: the OpenTelemetry Java agent, added to your Dockerfile with a pinned checksum.
|
|
50
|
+
- **Startup.** It loads OpenTelemetry when your app starts, in your Dockerfile or start script. New Dockerfile lines go after your last `RUN`, so build steps never load OpenTelemetry. Lines you already have, such as `NODE_OPTIONS`, stay as they are. For Python, it changes the start command only when your image installs the file that it changed.
|
|
51
|
+
- **Settings.** It adds 5 settings where your app keeps settings: your Dockerfile, your Kubernetes manifest or `otel.env`.
|
|
52
|
+
- `OTEL_SERVICE_NAME`
|
|
53
|
+
- `OTEL_EXPORTER_OTLP_ENDPOINT`
|
|
54
|
+
- `OTEL_EXPORTER_OTLP_PROTOCOL`
|
|
55
|
+
- `OTEL_METRICS_EXPORTER`
|
|
56
|
+
- `OTEL_LOGS_EXPORTER`
|
|
57
|
+
- **A record.** It writes `.uknows/setup.json`, so `remove` can undo exactly what it changed. This file has no secrets. Commit it.
|
|
58
|
+
|
|
59
|
+
For Go, PHP and Ruby, it adds the settings and prints the steps to do by hand.
|
|
60
|
+
|
|
61
|
+
If your app already uses OpenTelemetry, it adds only the settings. If your app sends data to another address, such as an OpenTelemetry Collector, it keeps that address and its settings and shows you what to change. If your app uses another APM agent, such as Datadog or New Relic, it stops and explains your options.
|
|
62
|
+
|
|
63
|
+
A frontend, such as a React app that nginx serves, gets no change. UKNOWS traces server apps.
|
|
64
|
+
|
|
65
|
+
## Your key
|
|
66
|
+
|
|
67
|
+
Your key goes in `OTEL_EXPORTER_OTLP_HEADERS`. Set it once for each environment as a secret on your platform. After setup, the tool prints the steps for the platform it found in your repo.
|
|
68
|
+
|
|
69
|
+
Never put the key in a file in your repo.
|
|
70
|
+
|
|
71
|
+
Right after setup, the tool asks for your key and checks it. To check it again later, run these 3 lines in bash. Paste your key when it asks. The key does not show on the screen and does not go in your shell history.
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
read -rsp 'Paste your UKNOWS key: ' UKNOWS_KEY; echo
|
|
75
|
+
export OTEL_EXPORTER_OTLP_HEADERS="x-uknows-key=$UKNOWS_KEY"
|
|
76
|
+
npx @uknows/setup check
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`check` asks UKNOWS which workspace and environment the key sends to, then sends 1 test span. A key that UKNOWS refuses gets its reason: not known, revoked, or a paused workspace. Apart from your package manager, the check is the only part of the tool that uses the network. Setup runs your package manager with install scripts turned off, so no code from your project or its packages runs. With a lockfile, npm and pnpm change only `package.json` and the lockfile.
|
|
80
|
+
|
|
81
|
+
## Commands and options
|
|
82
|
+
|
|
83
|
+
```text
|
|
84
|
+
npx @uknows/setup [setup] [options] Find your app, show the plan, then apply it.
|
|
85
|
+
npx @uknows/setup remove [options] Undo what setup changed.
|
|
86
|
+
npx @uknows/setup check [--json] Check your key and send 1 test span.
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
| Option | What it does |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `--dry-run` | Show the plan. Change nothing. |
|
|
92
|
+
| `--yes`, `-y` | Apply without asking. It never asks any question and does not check the key, so it is safe in scripts. |
|
|
93
|
+
| `--path <folder>` | The folder to set up. The default is the current folder. |
|
|
94
|
+
| `--all` | Set up every service folder in a monorepo. Each one gets its own `OTEL_SERVICE_NAME`. |
|
|
95
|
+
| `--service-name <name>` | The name of the service in UKNOWS. Use lowercase letters, digits and `-`. |
|
|
96
|
+
| `--json` | Print a JSON report. Without `--yes`, setup only plans. |
|
|
97
|
+
| `--force` | Run even when the repo has changes that are not committed. With `remove`, delete the record even when some changes could not be undone. |
|
|
98
|
+
| `--check` | The same as the `check` command. |
|
|
99
|
+
|
|
100
|
+
Setup stops when your repo has changes that are not committed, so you can review exactly what it changed with `git diff`. Commit or stash your changes first, or use `--force`.
|
|
101
|
+
|
|
102
|
+
With `--path`, setup still reads the deploy files at the top of the git repo, such as `k8s/` and `.github/workflows/`, to find where your app runs. If the folder is part of a JavaScript workspace, or its .NET package versions are set in a file above it, setup changes nothing and asks you to run it from the repo root. There, pick the service from the list, or use `--all`.
|
|
103
|
+
|
|
104
|
+
## Exit codes
|
|
105
|
+
|
|
106
|
+
| Code | Meaning |
|
|
107
|
+
|---|---|
|
|
108
|
+
| 0 | Done, or nothing to do. |
|
|
109
|
+
| 1 | Stopped or failed. Nothing changed. For example, another APM agent, a dirty repo, a key in a file that setup would change, or a package manager error. |
|
|
110
|
+
| 2 | Usage error, or you need to pick a service. In a script, pass `--yes`, and `--all` or `--path` for a monorepo. |
|
|
111
|
+
| 3 | You need to do 1 or more steps by hand. The tool prints them. |
|
|
112
|
+
|
|
113
|
+
## Undo
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
npx @uknows/setup remove
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`remove` runs your package manager to remove the packages that setup added. Then it puts back every line that setup changed and deletes the files that setup created. If you changed those lines after setup, it skips that file, tells you, and keeps the record so you can run `remove` again. If your package manager does not write `package.json` or the lockfile back byte for byte, `remove` names the file, so you can check it with `git diff`.
|
|
120
|
+
|
|
121
|
+
## Requirements
|
|
122
|
+
|
|
123
|
+
Node.js 18 or later, on macOS, Linux or Windows. The tool has no dependencies.
|
|
124
|
+
|
|
125
|
+
## Test addresses
|
|
126
|
+
|
|
127
|
+
Setup writes `OTEL_EXPORTER_OTLP_ENDPOINT` with the UKNOWS ingest address, and check asks the UKNOWS site about your key. To use a test copy of UKNOWS, set both addresses. The test copy's `/docs` page gives the command with them:
|
|
128
|
+
|
|
129
|
+
```sh
|
|
130
|
+
UKNOWS_SITE_URL=https://uknows-test.example.com UKNOWS_INGEST_ENDPOINT=https://ingest-test.example.com/otlp npx @uknows/setup
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Both must be https addresses. On your own computer, `http://127.0.0.1` and `http://localhost` work too. With only `UKNOWS_INGEST_ENDPOINT`, check sends the test span but does not ask which workspace the key sends to.
|
|
134
|
+
|
|
135
|
+
To build a package for a test environment, bake its addresses in, the same build settings that `/docs` uses. Do not commit the result:
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
VITE_UKNOWS_SITE_URL=https://uknows-test.example.com \
|
|
139
|
+
VITE_UKNOWS_INGEST_HOST=ingest-test.example.com \
|
|
140
|
+
node tools/sync-contract.mjs
|
|
141
|
+
npm pack
|
|
142
|
+
git checkout lib/contract-docs.mjs
|
|
143
|
+
```
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// npx @uknows/setup: add OpenTelemetry to an app so it sends traces to UKNOWS.
|
|
3
|
+
const major = Number(process.versions.node.split('.')[0])
|
|
4
|
+
if (major < 18) {
|
|
5
|
+
console.error(`uknows-setup needs Node.js 18 or later. This is Node.js ${process.versions.node}.`)
|
|
6
|
+
process.exit(1)
|
|
7
|
+
}
|
|
8
|
+
try {
|
|
9
|
+
const { main } = await import('../lib/cli.mjs')
|
|
10
|
+
process.exitCode = await main(process.argv.slice(2))
|
|
11
|
+
} catch (error) {
|
|
12
|
+
console.error(`Something went wrong: ${error?.message ?? error}`)
|
|
13
|
+
process.exitCode = 1
|
|
14
|
+
}
|
package/lib/check.mjs
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The check command: check the key from OTEL_EXPORTER_OTLP_HEADERS (or the
|
|
3
|
+
* key pasted after setup), and say what happened. 2 steps, the only network
|
|
4
|
+
* calls the CLI makes:
|
|
5
|
+
* 1. Ask the site which workspace and environment the key sends to (the
|
|
6
|
+
* ping route that "Check your key" on /docs uses). A refused key stops here.
|
|
7
|
+
* 2. Send 1 test span to the ingest address, as the app will.
|
|
8
|
+
* It uses node:http and node:https (fetch prints a warning on Node 18). The key
|
|
9
|
+
* never appears in the output.
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from 'node:crypto'
|
|
12
|
+
import { readFileSync } from 'node:fs'
|
|
13
|
+
import http from 'node:http'
|
|
14
|
+
import https from 'node:https'
|
|
15
|
+
import { BASH_STEP, CLI, KEY_CHECK, KEY_PROMPT, SECRET, TROUBLESHOOTING } from './contract.mjs'
|
|
16
|
+
import { ingestEndpoint, sameUknows, siteUrl } from './endpoint.mjs'
|
|
17
|
+
|
|
18
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
|
|
19
|
+
const CERT = /^(?:CERT_|ERR_TLS_CERT|UNABLE_TO_(?:VERIFY_LEAF_SIGNATURE|GET_ISSUER_CERT)|SELF_SIGNED_CERT_IN_CHAIN|DEPTH_ZERO_SELF_SIGNED_CERT|ERR_SSL_)/
|
|
20
|
+
const MAX_BODY = 65536
|
|
21
|
+
const ACCEPTED = 'UKNOWS accepted 1 test span.'
|
|
22
|
+
/** What each refusal of the ping route means, from the docs list ("ingest_key_invalid" and so on). */
|
|
23
|
+
const MEANING = new Map(KEY_CHECK.answers.map((a) => [/^[a-z_]+$/.test(a.answer) ? a.answer : null, a.meaning]).filter(([code]) => code))
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Check the key in OTEL_EXPORTER_OTLP_HEADERS from env (or options.headers), then send 1 test span.
|
|
27
|
+
* @param {{env?: Record<string, string|undefined>, headers?: string, timeoutMs?: number}} [options]
|
|
28
|
+
* @returns {Promise<import('./types.mjs').CheckResult>}
|
|
29
|
+
*/
|
|
30
|
+
export async function runCheck(options = {}) {
|
|
31
|
+
const { env = process.env, timeoutMs = 10000 } = options
|
|
32
|
+
const raw = options.headers ?? env[SECRET.name]
|
|
33
|
+
if (!raw || !raw.trim()) {
|
|
34
|
+
return result(2, null, [`${SECRET.name} is not set in this terminal.`, BASH_STEP,
|
|
35
|
+
'Run these 3 lines. Paste your key when it asks. The key does not show on the screen.',
|
|
36
|
+
` ${KEY_PROMPT}`, ` export ${SECRET.name}="${SECRET.header}=$UKNOWS_KEY"`, ' npx @uknows/setup check'])
|
|
37
|
+
}
|
|
38
|
+
const headers = parseHeaders(raw)
|
|
39
|
+
// Hide each header value as written and as decoded. A part without '=' may be a bare key: hide it whole.
|
|
40
|
+
const redact = redactor([...raw.split(',').map((part) => part.slice(part.indexOf('=') + 1)), ...Object.values(headers)])
|
|
41
|
+
const keyName = Object.keys(headers).find((name) => name.toLowerCase() === SECRET.header)
|
|
42
|
+
if (!keyName) {
|
|
43
|
+
return result(2, null, [`${SECRET.name} has no ${SECRET.header}. Use the format ${SECRET.value}. Remove spaces and quotes.`])
|
|
44
|
+
}
|
|
45
|
+
const endpoint = ingestEndpoint(env)
|
|
46
|
+
if (!endpoint) return result(1, null, [`${CLI.endpointEnv} must be an https address.`])
|
|
47
|
+
const site = siteUrl(env)
|
|
48
|
+
if (!site) return result(1, null, [`${CLI.siteEnv} must be an https address with no path, for example https://uknows.example.com.`])
|
|
49
|
+
|
|
50
|
+
// 1. Which workspace and environment the key sends to.
|
|
51
|
+
let ping = null
|
|
52
|
+
const lines = [], after = []
|
|
53
|
+
if (sameUknows(env)) {
|
|
54
|
+
const answer = await request(new URL(`${site}${CLI.pingPath}`), 'GET', { [SECRET.header]: headers[keyName] }, null, timeoutMs)
|
|
55
|
+
ping = explainPing(answer, site, redact)
|
|
56
|
+
if (ping.stop) return { ...result(1, answer.status ?? null, ping.lines), keyState: ping.keyState ?? null }
|
|
57
|
+
lines.push(...ping.lines)
|
|
58
|
+
} else {
|
|
59
|
+
after.push(`To also see which workspace the key sends to, set ${CLI.siteEnv} with ${CLI.endpointEnv}.`)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 2. 1 test span to the ingest address.
|
|
63
|
+
const url = new URL(`${endpoint}/v1/traces`)
|
|
64
|
+
const response = await request(url, 'POST', { ...headers, 'content-type': 'application/json' }, testSpan(env), timeoutMs)
|
|
65
|
+
if (response.error) return { ...result(1, null, [...lines, ...explainNetworkError(response.error, url, timeoutMs, env).map(redact), ...after]), ...named(ping) }
|
|
66
|
+
const sent = explainResponse(response, redact)
|
|
67
|
+
// Without the site's answer, the accepted span is what shows that the key works.
|
|
68
|
+
const spanLines = sent.lines.map((line) => (line === ACCEPTED && !ping?.workspace ? `${ACCEPTED} Your key works.` : line))
|
|
69
|
+
return { ...sent, ...named(ping, sent), lines: [...lines, ...spanLines, ...(sent.ok ? after : [])] }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The workspace and environment from the ping, when the ingest answer did not name them. */
|
|
73
|
+
function named(ping, sent = {}) {
|
|
74
|
+
return { workspace: sent.workspace ?? ping?.workspace ?? null, environment: sent.environment ?? ping?.environment ?? null, keyState: ping?.keyState ?? null }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** What the ping route said. stop: true when the key is refused, so no span is sent. */
|
|
78
|
+
export function explainPing({ status, error, body }, site, redact = (x) => x) {
|
|
79
|
+
const host = new URL(site).hostname
|
|
80
|
+
if (error) return { stop: false, lines: [`Could not ask ${host} which workspace the key sends to (${error.code || 'network error'}). Sending the test span anyway.`] }
|
|
81
|
+
const data = parse(body)
|
|
82
|
+
if (status === 200 && data?.workspace) {
|
|
83
|
+
const workspace = clean(data.workspace.name ?? data.workspace.id, redact)
|
|
84
|
+
const environment = clean(data.environmentLabel ?? data.environment, redact)
|
|
85
|
+
const lines = [`Your key works. It sends data to ${workspace}${environment ? `, environment ${environment}` : ''}.`]
|
|
86
|
+
if (data.keyState === 'retiring') lines.push(`A new key replaced this key. It stops working${data.retiresAt ? ` at ${clean(String(data.retiresAt), redact)}` : ' soon'}. Set the new key.`)
|
|
87
|
+
if (data.status === 'paused') lines.push('Your workspace is paused.')
|
|
88
|
+
return { stop: false, workspace, environment, keyState: clean(data.keyState, redact), lines }
|
|
89
|
+
}
|
|
90
|
+
const code = typeof data?.error === 'string' ? data.error : null
|
|
91
|
+
if ((status === 401 || status === 403) && code) {
|
|
92
|
+
const why = code === 'ingest_key_missing' ? 'The key is empty.' : MEANING.get(code) ?? `UKNOWS refused the key (${code}).`
|
|
93
|
+
return { stop: true, keyState: code === 'ingest_key_revoked' ? 'revoked' : null, lines: [`UKNOWS did not accept the key (${code}).`, why] }
|
|
94
|
+
}
|
|
95
|
+
if (status === 429) return { stop: false, lines: [`${host} says: too many checks from your address. Sending the test span anyway.`] }
|
|
96
|
+
return { stop: false, lines: [`${host} did not say which workspace the key sends to (status ${status}). Sending the test span anyway.`] }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Header pairs from 'k=v,k2=v2'. Each part splits on its first '=' and is percent-decoded, as the OTLP spec says. */
|
|
100
|
+
export function parseHeaders(value) {
|
|
101
|
+
const out = {}
|
|
102
|
+
for (const part of String(value).split(',')) {
|
|
103
|
+
const at = part.indexOf('=')
|
|
104
|
+
if (at < 1) continue
|
|
105
|
+
const name = decode(part.slice(0, at).trim())
|
|
106
|
+
if (name) out[name] = decode(part.slice(at + 1).trim())
|
|
107
|
+
}
|
|
108
|
+
return out
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** What to print for a network error. Exported for tests: DNS and TLS failures are hard to cause offline. */
|
|
112
|
+
export function explainNetworkError(error, url, timeoutMs, env = {}) {
|
|
113
|
+
const code = error?.code ?? ''
|
|
114
|
+
const port = url.port || (url.protocol === 'https:' ? '443' : '80')
|
|
115
|
+
const host = url.hostname
|
|
116
|
+
const proxy = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'].some((k) => env[k])
|
|
117
|
+
if (CERT.test(code)) return [`Cannot check the TLS certificate of ${host} (${code}).`, 'A proxy may be in the way. This tool does not use HTTPS_PROXY.']
|
|
118
|
+
const seconds = Math.round(timeoutMs / 100) / 10
|
|
119
|
+
const lines = [
|
|
120
|
+
code === 'ENOTFOUND' || code === 'EAI_AGAIN' ? `Cannot find ${host}. Check DNS.`
|
|
121
|
+
: code === 'ECONNREFUSED' ? `${host} refused the connection on port ${port}.`
|
|
122
|
+
: code === 'UKNOWS_TIMEOUT' || code === 'ETIMEDOUT' ? `No answer in ${seconds} ${seconds === 1 ? 'second' : 'seconds'}.`
|
|
123
|
+
: code === 'ECONNRESET' || code === 'EPIPE' ? `The connection to ${host} closed before UKNOWS answered.`
|
|
124
|
+
: code === 'EHOSTUNREACH' || code === 'ENETUNREACH' ? `Cannot reach ${host}. Check your network.`
|
|
125
|
+
: /^ERR_INVALID_(?:CHAR|HTTP_TOKEN)/.test(code) ? `${SECRET.name} has a character that is not allowed in a header.`
|
|
126
|
+
: `Cannot reach ${host} (${code || 'unknown error'}).`,
|
|
127
|
+
]
|
|
128
|
+
if (proxy) lines.push('This tool does not use HTTPS_PROXY. Run the check on a network that can reach UKNOWS directly.')
|
|
129
|
+
return lines
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// --- request and response ---------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
function request(url, method, headers, body, timeoutMs) {
|
|
135
|
+
return new Promise((resolve) => {
|
|
136
|
+
let done = false, timer = null, req
|
|
137
|
+
const finish = (value) => { if (!done) { done = true; clearTimeout(timer); resolve(value) } }
|
|
138
|
+
try {
|
|
139
|
+
req = (url.protocol === 'https:' ? https : http).request(url, {
|
|
140
|
+
method, agent: false,
|
|
141
|
+
headers: { ...headers, ...(body === null ? {} : { 'content-length': Buffer.byteLength(body) }), 'user-agent': `uknows-setup/${VERSION}` },
|
|
142
|
+
}, (res) => {
|
|
143
|
+
const chunks = []
|
|
144
|
+
let size = 0
|
|
145
|
+
res.on('data', (chunk) => { if (size < MAX_BODY) { chunks.push(chunk); size += chunk.length } })
|
|
146
|
+
res.on('end', () => finish({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks).toString('utf8').slice(0, MAX_BODY) }))
|
|
147
|
+
res.on('error', (error) => finish({ error }))
|
|
148
|
+
})
|
|
149
|
+
} catch (error) { resolve({ error }); return }
|
|
150
|
+
timer = setTimeout(() => { finish({ error: { code: 'UKNOWS_TIMEOUT' } }); req.destroy() }, timeoutMs)
|
|
151
|
+
req.on('error', (error) => finish({ error }))
|
|
152
|
+
req.end(body ?? undefined)
|
|
153
|
+
})
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function explainResponse({ status, headers, body }, redact) {
|
|
157
|
+
const data = parse(body)
|
|
158
|
+
if (status >= 200 && status < 300) {
|
|
159
|
+
const workspace = clean(data?.workspace, redact) ?? clean(headers['x-uknows-workspace'], redact)
|
|
160
|
+
const environment = clean(data?.environment, redact) ?? clean(headers['x-uknows-environment'], redact)
|
|
161
|
+
const lines = [workspace && environment ? `Reached ${workspace} / ${environment}.` : workspace ? `Reached ${workspace}.` : ACCEPTED]
|
|
162
|
+
const rejected = Number(data?.partialSuccess?.rejectedSpans ?? 0)
|
|
163
|
+
if (rejected > 0) lines.push(`UKNOWS did not keep the test span: ${clean(data.partialSuccess.errorMessage, redact) ?? 'no reason given'}.`)
|
|
164
|
+
return { ok: true, status, workspace, environment, lines, exit: 0 }
|
|
165
|
+
}
|
|
166
|
+
const steps = (id) => TROUBLESHOOTING.find((t) => t.id === id)?.steps ?? []
|
|
167
|
+
if (status === 401) return result(1, status, [`UKNOWS did not accept the key (status 401).`, ...steps('unauthorized')])
|
|
168
|
+
if (status === 403) return result(1, status, [`UKNOWS refused the key (status 403).`, ...steps('forbidden')])
|
|
169
|
+
const textual = !data && /json|text/i.test(String(headers['content-type'] ?? ''))
|
|
170
|
+
const message = clean(typeof data?.message === 'string' ? data.message : textual ? body : null, redact)
|
|
171
|
+
const lines = [`UKNOWS answered with status ${status}.`]
|
|
172
|
+
if (message) lines.push(message.length > 200 ? `${message.slice(0, 197)}...` : message)
|
|
173
|
+
if ([429, 502, 503, 504].includes(status)) lines.push('Try again in 1 minute.')
|
|
174
|
+
return result(1, status, lines)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 1 span in OTLP/JSON: hex ids, integer enums, int64 values as decimal strings. */
|
|
178
|
+
function testSpan(env) {
|
|
179
|
+
const hex = (bytes) => { let id; do id = randomBytes(bytes).toString('hex'); while (/^0+$/.test(id)); return id }
|
|
180
|
+
const start = BigInt(Date.now()) * 1000000n
|
|
181
|
+
return JSON.stringify({ resourceSpans: [{
|
|
182
|
+
resource: { attributes: [{ key: 'service.name', value: { stringValue: env.OTEL_SERVICE_NAME || 'uknows-setup-check' } }] },
|
|
183
|
+
scopeSpans: [{ scope: { name: '@uknows/setup', version: VERSION }, spans: [{
|
|
184
|
+
traceId: hex(16), spanId: hex(8), name: 'uknows setup check', kind: 1,
|
|
185
|
+
startTimeUnixNano: String(start), endTimeUnixNano: String(start + 1000000n),
|
|
186
|
+
attributes: [{ key: 'uknows.check', value: { boolValue: true } }],
|
|
187
|
+
}] }],
|
|
188
|
+
}] })
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// --- helpers ------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
function result(exit, status, lines) {
|
|
194
|
+
return { ok: false, status, workspace: null, environment: null, lines, exit }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Replaces every form of the key with <key>, longest first, so a server that echoes it back cannot leak it. */
|
|
198
|
+
function redactor(values) {
|
|
199
|
+
const secrets = [...new Set(values.map((v) => String(v ?? '').trim()))].filter((v) => v.length >= 4).sort((a, b) => b.length - a.length)
|
|
200
|
+
return (line) => secrets.reduce((out, secret) => out.split(secret).join(SECRET.placeholder), line)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** A short single-line text from the server, or null. */
|
|
204
|
+
function clean(value, redact) {
|
|
205
|
+
if (typeof value !== 'string') return null
|
|
206
|
+
const out = redact(value.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim())
|
|
207
|
+
return out ? out.slice(0, 200) : null
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function decode(text) { try { return decodeURIComponent(text) } catch { return text } }
|
|
211
|
+
function parse(body) { try { return JSON.parse(body) } catch { return null } }
|