Skip to content

Commit de9c8b8

Browse files
Merge pull request #14 from VKCOM/new-doc
Actualize documentation
2 parents 4d1c89d + e079fb8 commit de9c8b8

File tree

5 files changed

+249
-11
lines changed

5 files changed

+249
-11
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ To add the devices you will need a running provider instance and one or multiple
1919
The easiest way to run the provider is to do
2020
1) npm ci
2121
2) npm link --force
22-
3) stf provider --connect-sub "tcp://localhost:7250" --connect-push "tcp://localhost:7270" --storage-url "http://localhost:8082"
22+
3) MONGODB_PORT_27017_TCP=mongodb://localhost:27017 stf provider --connect-sub "tcp://localhost:7250" --connect-push "tcp://localhost:7270" --storage-url "http://localhost:8082"
2323

2424
Note: some features require direct access to the provider instance from the browser, so if you are running the provider on a different machine - make sure you pass accessible url to the --public-ip.
2525

README.ru.md

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
# Добро пожаловать в репозиторий VK DeviceHub!
2+
<img src="res/common/logo/exports/readmeLogo.svg" style="width:300px;height:100px;" alt="VK Devicehub">
3+
4+
## О проекте
5+
6+
VK DeviceHub - это форк проекта DeviceFarmer/stf, разработанный в компании VK.
7+
8+
Если у вас есть идеи, предложения или вы хотите принять участие в разработке, мы приглашаем вас присоединиться к нашему чату разработчиков ([ссылка](https://vk.me/join/QCCJfaPu544UDzXgQrXe1jNVMyVEdh9bFZg=)).
9+
10+
Презентацию о нашем продукте на конференции Heisenbug 2024 вы можете посмотреть по этой ссылке:
11+
[Презентация на конференции Heisenbug 2024](https://heisenbug.ru/talks/cee3ec59796e43f6a3d4ae508db157d3/?referer=/schedule/days/)
12+
13+
Переведено с помощью DeepL.com (бесплатная версия)
14+
<img src="doc/showcase.png" alt="VK Devicehub">
15+
16+
## Как запустить?
17+
18+
1) Установите Docker
19+
2) Запустите `docker compose -f docker-compose-prod.yaml --env-file scripts/variables.env up` и будет поднята локальная инсталляция на порту 8082. См [docker-compose-prod.yaml](./docker-compose-prod.yaml).
20+
21+
Осталось только добавить в ферму девайсы
22+
Для этого нужно запустить провайдер и иметь работающее adb соединение с устройством.
23+
Самый простой способ это:
24+
1) Убедиться что установлен питон и в нём установлен setuptools (нужен для одной из наших npm зависимостей)
25+
2) `npm ci` - скачать и установить зависимости
26+
3) `npm link --force` - Добавить исполняемый файл в текущий PATH
27+
4) `MONGODB_PORT_27017_TCP=mongodb://localhost:27017 stf provider --connect-sub "tcp://localhost:7250" --connect-push "tcp://localhost:7270" --storage-url "http://localhost:8082"`
28+
29+
Замечание:
30+
Некоторый функционал требует наличия прямого доступа до провайдера из браузера. Поэтому в случае сложных инсталляций не забудьте передать внешнедоступный url в параметр --public-url
31+
32+
## Функционал
33+
34+
### База данных
35+
- **Использование MongoDB**: Использует MongoDB вместо RethinkDB для повышения производительности и гибкости.
36+
37+
### Поддержка операционных систем
38+
- **Android**:
39+
- Поддерживает широкий спектр версий от 2.3.3 (SDK уровня 10) до 14 (SDK уровня 34).
40+
- Совместимость с Wear 5.1 и Fire OS, CyanogenMod и другими дистрибутивами на базе Android.
41+
- **Не требуются Root права**: Все функции работают без необходимости получения root-доступа.
42+
43+
### Удаленное управление и просмотр экрана
44+
- **Дистанционное управление**: Беспрепятственное управление любым устройством из браузера.
45+
- **Просмотр экрана в реальном времени**: Скорость обновления 30-40 кадров в секунду, в зависимости от технических характеристик устройства и версии Android.
46+
- **Поддержка вращения**: Поддержка автоматической и ручной регулировки поворота для оптимального просмотра.
47+
- **Ввод с клавиатуры**: Ввод текста непосредственно с клавиатуры с поддержкой мета-клавиш.
48+
- **Копирование и вставка**: Включает поддержку операций копирования и вставки, хотя на старых устройствах может потребоваться ручная вставка.
49+
- **Поддержка мультитач**: Обеспечивает взаимодействие с мультитач на сенсорных экранах и поддержку жестов на обычных экранах.
50+
- **Установка с перетаскиванием**: Легкая установка и запуск файлов `.apk` с помощью функции drag-and-drop.
51+
- **Обратная переадресация портов**: Доступ к локальному серверу непосредственно с устройства, даже через разные сети.
52+
- **Веб-браузинг**: Открывайте веб-сайты в любом браузере с помощью функции определения установленных браузеров в режиме реального времени.
53+
54+
### Управление устройствами
55+
- **Мониторинг инвентаря устройств**: Следите за подключенными устройствами, уровнем заряда батареи и характеристиками оборудования.
56+
- **Поиск устройств**: Быстрый поиск устройств по различным признакам с помощью мощных поисковых запросов.
57+
- **Идентификация пользователей**: Идентификация пользователей, подключенных к устройствам, и мониторинг использования устройств.
58+
- **Поиск устройства**: Отображение идентификационной информации на экране для облегчения определения местоположения устройства.
59+
- **Отслеживание заряда батареи**: Отслеживайте уровень заряда батареи и состояние каждого устройства.
60+
61+
### Системы бронирования и разделения
62+
- **Система разделения**: Выделяйте устройства для различных проектов или организаций на неограниченный срок.
63+
- **Система бронирования**: Резервирование устройств для пользователей на определенный период времени.
64+
- **Управление группами**: Организуйте устройства, пользователей и расписания в группы для эффективного управления.
65+
- **Подробная документация**: Инструкции по использованию функций резервирования и разделения см. в подробной документации.
66+
67+
**Управление групповыми запасами
68+
- **Мониторинг состояния групп**: Отслеживайте состояние групп, включая активность, готовность и статус ожидания.
69+
- **Поиск групп**: Поиск и фильтрация групп по различным атрибутам для удобства управления.
70+
- **Связь с группами**: Связь с владельцами групп по электронной почте прямо из интерфейса.
71+
72+
### Управление устройствами и пользователями
73+
- **Управление устройствами**: Поиск устройств, удаление устройств на основе фильтров, управление аннотациями и элементами управления устройствами.
74+
- **Управление пользователями**: Создание, поиск и удаление пользователей, управление правами пользователей и установка групповых квот.
75+
- **Общение с пользователями**: Связь с пользователями по электронной почте и создание пользователей служб через интерфейс командной строки (CLI).
76+
77+
### REST API
78+
- **Простой REST API**: Программный доступ к функциям системы с помощью простого REST API. Подробности см. в документации по API.
79+
80+
81+
## Краткое замечание о безопасности
82+
83+
Изначально STF был внутренним проектом без надежных мер безопасности и шифрования.
84+
Однако мы устранили различные проблемы и общие уязвимости и уязвимости (CVE). Кроме того, мы обновили зависимости, в которых были обнаружены CVE.
85+
86+
Мы приветствуем вклад в дальнейшее повышение безопасности проекта.
87+
88+
## Building
89+
90+
Once you have installed all the requirements, you can proceed to fetch the remaining dependencies.
91+
92+
Start by fetching all NPM and Bower modules:
93+
94+
```bash
95+
npm install
96+
```
97+
98+
Additionally, you may want to link the module so that you can access the `stf` command directly from the command line:
99+
100+
```bash
101+
npm link
102+
```
103+
104+
With these steps completed, you should have a functional installation ready for local development.
105+
106+
107+
## Running
108+
109+
STF consists of several independent processes that typically need to be launched separately. In our setup, each of these processes is its own unit. Refer to [DEPLOYMENT.md](doc/DEPLOYMENT.md) and [Setup Examples](https://github.com/devicefarmer/setup-examples) for more details.
110+
111+
However, for development purposes, there's a handy command to quickly launch all the required processes along with a mock login implementation. Please note that you **must** have MongoDB running beforehand.
112+
113+
```bash
114+
docker run --rm -d -p 27017:27017 -h 127.0.0.1 --name mongo mongo:6.0.10 --replSet=test && sleep 4 && docker exec mongo mongosh --eval "rs.initiate();"
115+
```
116+
117+
This command will start MongoDB locally.
118+
119+
In addition to native user accounts, STF provides an administrator level with increased rights on certain features (e.g., booking & partitioning systems, management of users & devices, etc.). The built-in administrator user has the following default credentials:
120+
- Name: `administrator`
121+
- Email: `administrator@fakedomain.com`
122+
123+
Another built-in object is the root standard group to which users and devices belong the first time they register with the STF database. Its default name is `Common`.
124+
125+
These built-in objects are created in the STF database if they do not already exist.
126+
127+
You can override the default values of these built-in objects by setting the following environment variables before initializing the STF database through the `stf local` or `stf migrate` commands:
128+
- Root standard group name: `STF_ROOT_GROUP_NAME`
129+
- Administrator user name: `STF_ADMIN_NAME`
130+
- Administrator user email: `STF_ADMIN_EMAIL`
131+
132+
Once configured, you're ready to start up STF itself:
133+
134+
```bash
135+
stf local
136+
```
137+
138+
After the [webpack](http://webpack.github.io/) build process has finished (which may take a moment), your private STF instance should be accessible at [http://localhost:7100](http://localhost:7100). If you had devices connected before running the command, those devices should now be available for use. Otherwise, check your console for any errors. You can plug in or unplug devices at any time.
139+
140+
If you need to access STF from other machines, you can use the `--public-ip` option for quick testing:
141+
142+
```bash
143+
stf local --public-ip <your_internal_network_ip_here>
144+
```
145+
146+
147+
## Updating
148+
149+
To update your development version, simply pull the repository and run `npm install` again. Occasionally, you may need to remove the entire `node_modules` and `res/bower_components` folder to prevent NPM or Bower from complaining about version mismatches.
150+
151+
## FAQ
152+
153+
### I already use STF with RethinkDB. How can I migrate to MongoDB?
154+
155+
You need to set up MongoDB and then run:
156+
157+
```bash
158+
stf migrate-to-mongo
159+
```
160+
161+
### Can I deploy STF to actual servers?
162+
163+
Yes, please refer to [DEPLOYMENT.md](doc/DEPLOYMENT.md) and [Setup Examples](https://github.com/devicefarmer/setup-examples) for deployment instructions.
164+
165+
### Will I have to change battery packs all the time?
166+
167+
Battery packs in devices that are in constant use typically last from 4 to 8 months. After this period, they begin to swell.
168+
Expanded batteries should be replaced as soon as possible. Note that this issue isn't specific to STF; it's a common occurrence over time.
169+
If you have come up with an interesting solution for running devices without batteries, please [let us know](https://vk.me/join/QCCJfaPu544UDzXgQrXe1jNVMyVEdh9bFZg=).
170+
171+
Ensure that your devices are set up to allow the display to turn off entirely after a short timeout, around 30 seconds or so. STF will wake it up when necessary. Otherwise, you risk reducing the lifetime of your device.
172+
173+
Note that you may encounter a problem if your USB hubs cannot both provide enough power for charging and support a data connection at the same time (data connections require power too). This can cause a device to stop charging when being used, resulting in many charging cycles. If this happens, you will need to [get a better USB hub](#recommended-hardware).
174+
175+
### Once I have the system running, can I pretty much leave it as is, or is manual intervention required?
176+
177+
In our experience, the system runs smoothly most of the time, with occasional issues mostly related to USB connections. Typically, you'll need to intervene about once a week.
178+
179+
The most common issue is when a device loses all its active USB connections momentarily. While errors may appear in the logs, the worker process will usually recover or get respawned automatically, requiring no action from your side.
180+
181+
However, there are some common errors that do require manual intervention:
182+
183+
* **One device worker keeps getting respawned all the time**
184+
- Rebooting the device usually resolves this issue. If the device stays online long enough, you might be able to reboot it from the UI. Otherwise, SSH into the server and manually run `adb reboot`.
185+
- This could indicate USB problems, and the device may need to be relocated. Simplifying your setup can reduce such issues. Refer to [troubleshooting](#troubleshooting).
186+
- We're working on implementing periodic automatic restarts and better graceful recovery to mitigate this issue.
187+
188+
* **A whole group of devices keeps dying at once**
189+
- These devices are likely connected to the same USB hub, which could be faulty, or there may be compatibility issues. This often occurs with USB 3.0 hubs or USB extension cards. See [recommended hardware](#recommended-hardware).
190+
191+
* **A device that should be online is not showing up in the list or is showing up as disconnected**
192+
- Refer to [troubleshooting](#troubleshooting) for assistance.
193+
194+
### How do I uninstall STF from my device?
195+
196+
When you unplug your device, all STF utilities except STFService stop running automatically. There's no harm in force stopping or uninstalling it.
197+
198+
To uninstall the STFService, run the following command:
199+
200+
```bash
201+
adb uninstall jp.co.cyberagent.stf
202+
```
203+
204+
You may also want to remove our support binaries, although they won't run unless the device is connected to STF. You can do this as follows:
205+
206+
```bash
207+
adb shell rm /data/local/tmp/minicap \
208+
/data/local/tmp/minicap.so \
209+
/data/local/tmp/minitouch \
210+
/data/local/tmp/minirev
211+
```
212+
213+
Your device is now clean.
214+
215+
216+
### Scrcpy
217+
218+
If you want use scrcpy instead minicap run app with next command(Scrcpy functionality is in unstable state yet):
219+
220+
```bash
221+
stf local --need-scrcpy true
222+
```
223+
224+
## Testing
225+
226+
Refer to [TESTING.md](TESTING.md) for testing instructions.
227+
228+
## Contributing
229+
230+
To contribute, please read the guidelines outlined in [CONTRIBUTING.md](CONTRIBUTING.md).
231+
232+
## License
233+
234+
For licensing information, please see [LICENSE](LICENSE).
235+
236+
Copyright © 2024 V Kontakte LLC. All Rights Reserved.

docker-compose-prod.yaml

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
version: "3"
22
networks:
3-
devicehub:
3+
devicehub:
44

55
services:
66
nginx:
@@ -23,17 +23,19 @@ services:
2323
image: mongo:6.0.10
2424
hostname: mongo1
2525
container_name: mongo1
26-
entrypoint: [ "mongod", "--replSet", "myReplicaSet", "--bind_ip", "localhost,mongo1" ]
26+
ports:
27+
- 27017:27017
28+
entrypoint: ["mongod", "--replSet", "myReplicaSet", "--bind_ip_all"]
2729
mongo2:
2830
image: mongo:6.0.10
2931
hostname: mongo2
3032
container_name: mongo2
31-
entrypoint: [ "mongod", "--replSet", "myReplicaSet", "--bind_ip", "localhost,mongo2" ]
33+
entrypoint: ["mongod", "--replSet", "myReplicaSet", "--bind_ip_all"]
3234
mongo3:
3335
image: mongo:6.0.10
3436
hostname: mongo3
3537
container_name: mongo3
36-
entrypoint: [ "mongod", "--replSet", "myReplicaSet", "--bind_ip", "localhost,mongo3" ]
38+
entrypoint: ["mongod", "--replSet", "myReplicaSet", "--bind_ip_all"]
3739
mongosetup:
3840
image: mongo:6.0.10
3941
container_name: mongosetup
@@ -44,7 +46,7 @@ services:
4446
volumes:
4547
- ./scripts/mongo_setup.sh:/scripts/mongo_setup.sh
4648
restart: "no"
47-
entrypoint: [ "bash", "/scripts/mongo_setup.sh" ]
49+
entrypoint: ["bash", "/scripts/mongo_setup.sh"]
4850
devicehub-migrate:
4951
build: .
5052
image: devicehub

scripts/mongo_setup.sh

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@
11
#!/bin/bash
22
sleep 10
33

4-
mongosh --host 172.88.0.2:27017 <<EOF
4+
mongosh --host mongo1:27017 <<EOF
55
var cfg = {
66
"_id": "myReplicaSet",
77
"version": 1,
88
"members": [
99
{
1010
"_id": 0,
11-
"host": "172.88.0.2:27017",
11+
"host": "mongo1:27017",
1212
"priority": 2
1313
},
1414
{
1515
"_id": 1,
16-
"host": "172.88.0.3:27017",
16+
"host": "mongo2:27017",
1717
"priority": 0
1818
},
1919
{
2020
"_id": 2,
21-
"host": "172.88.0.4:27017",
21+
"host": "mongo3:27017",
2222
"priority": 0
2323
}
2424
]

scripts/variables.env

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
STF_SECRET=nosecret
22
STF_URL=http://localhost:8082
3-
MONGODB_PORT_27017_TCP=mongodb://172.88.0.2:27017
3+
MONGODB_PORT_27017_TCP=mongodb://mongo1:27017
44
AUTH_TYPE=auth-mock
55
AUTH_URL=auth/mock/

0 commit comments

Comments
 (0)