Compare commits

..

29 Commits

Author SHA1 Message Date
Xinwei Xiong (cubxxw) 87893dece2 feat: optimize config
Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
2024-01-23 17:19:52 +08:00
Xinwei Xiong (cubxxw) bd5e063140 feat: complete openim source deployment rpc start timeout 2024-01-23 16:07:59 +08:00
Xinwei Xiong (cubxxw) cc8ce6f69a openim-building-an-efficient-version-control-and-testing-workflow 2024-01-23 10:10:04 +08:00
Xinwei Xiong (cubxxw) ccfbccd345 feat: replace mongo database openIM_v3 to openim_v3 2024-01-22 18:16:06 +08:00
dependabot[bot] fa55c44113 feat(deps): bump golang.org/x/crypto from 0.14.0 to 0.17.0 (#1579)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.14.0 to 0.17.0.
- [Commits](https://github.com/golang/crypto/compare/v0.14.0...v0.17.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-21 08:51:21 +00:00
Xinwei Xiong e182d5e7df feat: optimize mac deployment scripts (#1795) 2024-01-21 04:13:31 +00:00
Xinwei Xiong 7155d1acb7 feat: Enhance Script Details and Add MacOS Compatibility with Documentation Updates (#1794)
* feat: fix a portion of get path

* feat: optimize mac deployment scripts
2024-01-21 02:49:08 +00:00
Brabem 907104701a fix: change the afterSendSingleMsg config and fix CallbackSingleMsgRead unused problem (#1790)
* fix: open the afterSendSingleMsg config

* fix: fix the CallbackSingleMsgRead unused
2024-01-19 15:50:33 +00:00
AndrewZuo01 19f5c94d25 fix: update nick name field for get_user (#1786)
* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* fix bugs

* fix bugs

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* Update go.mod

* Update friend.go

* debug

* debug

* debug

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* I cannot solve todo in test.sh

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* Update go.mod

* fix group notification

* fix group notification

* update openimsdk tools

* update openim server remove duplicate code

* update openim server remove duplicate code

* update user command get

* update user command get

* update response of callback response error

* update black ex

* update join group ex

* update user pb2map

* update go sum

* update go sum

* update updateUserInfoEx

* update updateUserInfoEx

* update updateUserInfoEx add callback functions

* fix dismiss group function

* fix dismiss group function

* fix dismiss group function

* fix dismiss group function

* update pin friend to update friend

* fix go mod

* fix err golangci-lint

* fix UserPb2DBMap

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* fix callback

* fix go.mod

* fix debug

* fix bugs

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* fix updateUserInfoEx

* fix updateUserInfoEx

* modify go.mod

* fix updateUserInfoEx

* fix updateUserInfoEx

* fix: fix the bug

* fix: fix the imAdmin permission and searchNoficitaion resp

* fix updateUserInfoEx

* 2023 Annual Summary Reflections and Aspirations

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: dissmissGroup and lack of keyword bug (#1678)

* Update docker-start-all.sh

* Update env-template.yaml

* update user command notification

* Update docker-start-all.sh

* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update user command get all notification

* update user command get all notification

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix typing cause callback

* add ex to usercommand

* add ex to usercommand

* update updatefriends

* fix updatefriend map

* fix updatefriend FriendsInfoUpdateNotification

* fix push online and offline user, but why typing trigger callback push?

* fix push online and offline user, but why typing trigger callback push?

* update user command record not found and user access check

* update user command get all user access check

* update go.mod

* fix callback name and place

* fix: fix some bug

* fix: group messages sync failed.

* upadtae callback test

* fix callback typing

* fix callback typing

* fix callback typing

* fix callback typing

* fix lint on processusercommand

* fix: fix the valiable name

* fix: fix the getSortedConversation api

* fix: fix the mongo search error

* fix: GroupApplicationAcceptedNotification

(cherry picked from commit 4c3c4555a3)

* fix: GroupApplicationAcceptedNotification

* fix update friends

* fix pageFindUser

* fix pageFindUser

* fix pageFindUser

* fix pageFindUser

* Delete .devcontainer directory

* revert

* more powerful PageFindUserWithKeyword

* more powerful PageFindUserWithKeyword

* more powerful PageFindUserWithKeyword

* bug: update nickname

* bug: update nickname

---------

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
Co-authored-by: Xinwei Xiong <3293172751@qq.com>
Co-authored-by: luhaoling <2198702716@qq.com>
Co-authored-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
Co-authored-by: Brabem <69128477+luhaoling@users.noreply.github.com>
Co-authored-by: OpenIM Bot <124379614+kubbot@users.noreply.github.com>
Co-authored-by: OpenIM Robot <139873238+openimbot@users.noreply.github.com>
Co-authored-by: Gordon <46924906+FGadvancer@users.noreply.github.com>
Co-authored-by: withchao <993506633@qq.com>
2024-01-19 15:49:57 +00:00
Xinwei Xiong 2a5129b1ae Update docker-compose.yaml support arm/v6, arm/v8 (#1776) 2024-01-16 13:49:27 +00:00
AndrewZuo01 080ddb82cd fix(main): add more cases for get_users api, so it accept users in older version. feat(main): also add search functionality (#1751)
* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* fix bugs

* fix bugs

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* Update go.mod

* Update friend.go

* debug

* debug

* debug

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* I cannot solve todo in test.sh

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* Update go.mod

* fix group notification

* fix group notification

* update openimsdk tools

* update openim server remove duplicate code

* update openim server remove duplicate code

* update user command get

* update user command get

* update response of callback response error

* update black ex

* update join group ex

* update user pb2map

* update go sum

* update go sum

* update updateUserInfoEx

* update updateUserInfoEx

* update updateUserInfoEx add callback functions

* fix dismiss group function

* fix dismiss group function

* fix dismiss group function

* fix dismiss group function

* update pin friend to update friend

* fix go mod

* fix err golangci-lint

* fix UserPb2DBMap

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* fix callback

* fix go.mod

* fix debug

* fix bugs

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* fix updateUserInfoEx

* fix updateUserInfoEx

* modify go.mod

* fix updateUserInfoEx

* fix updateUserInfoEx

* fix: fix the bug

* fix: fix the imAdmin permission and searchNoficitaion resp

* fix updateUserInfoEx

* 2023 Annual Summary Reflections and Aspirations

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: dissmissGroup and lack of keyword bug (#1678)

* Update docker-start-all.sh

* Update env-template.yaml

* update user command notification

* Update docker-start-all.sh

* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update user command get all notification

* update user command get all notification

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix typing cause callback

* add ex to usercommand

* add ex to usercommand

* update updatefriends

* fix updatefriend map

* fix updatefriend FriendsInfoUpdateNotification

* fix push online and offline user, but why typing trigger callback push?

* fix push online and offline user, but why typing trigger callback push?

* update user command record not found and user access check

* update user command get all user access check

* update go.mod

* fix callback name and place

* fix: fix some bug

* fix: group messages sync failed.

* upadtae callback test

* fix callback typing

* fix callback typing

* fix callback typing

* fix callback typing

* fix lint on processusercommand

* fix: fix the valiable name

* fix: fix the getSortedConversation api

* fix: fix the mongo search error

* fix: GroupApplicationAcceptedNotification

(cherry picked from commit 4c3c4555a3)

* fix: GroupApplicationAcceptedNotification

* fix update friends

* fix pageFindUser

* fix pageFindUser

* fix pageFindUser

* fix pageFindUser

* Delete .devcontainer directory

* revert

* more powerful PageFindUserWithKeyword

* more powerful PageFindUserWithKeyword

* more powerful PageFindUserWithKeyword

---------

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
Co-authored-by: Xinwei Xiong <3293172751@qq.com>
Co-authored-by: luhaoling <2198702716@qq.com>
Co-authored-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
Co-authored-by: Brabem <69128477+luhaoling@users.noreply.github.com>
Co-authored-by: OpenIM Bot <124379614+kubbot@users.noreply.github.com>
Co-authored-by: OpenIM Robot <139873238+openimbot@users.noreply.github.com>
Co-authored-by: Gordon <46924906+FGadvancer@users.noreply.github.com>
Co-authored-by: withchao <993506633@qq.com>
2024-01-16 06:34:41 +00:00
Xinwei Xiong 64d6b04320 feat: add openim docker compose deployment github comment (#1769)
* feat: add openim v3.4 and v3.5 changelog

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim github comment

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: fix openim docker compose images version form github comment

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: fix openim docker compose images version form github comment

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

---------

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
2024-01-15 08:39:44 +00:00
Xinwei Xiong 98d3646167 Stability Enhancement: Pin Docker Compose Images for minio and openim-web (#1762)
* Update docker-compose.yml

* Update docker-compose.yml

* Update docker-compose.yml
2024-01-13 01:38:52 +00:00
Xinwei Xiong fdf055d328 fix: mac deployment (#1761) 2024-01-12 14:02:56 +00:00
Xinwei Xiong a24eedb66d Update docker-compose.yml (#1759) 2024-01-12 13:17:45 +00:00
Xinwei Xiong 0375361294 Rename README.md to README.md (#1757) 2024-01-12 12:12:38 +00:00
AndrewZuo01 955520471f Rename devcontainer.json to devcontainer.json (#1756) 2024-01-12 10:58:29 +00:00
Xinwei Xiong c795304df1 🚀 Enhancements in Offline Deployment Documentation, CICD Process Upgrades, Deployment Optimization, and Additional Fixes (#1721)
* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: support openim prom enbels

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add go formity checker

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim offline deployment docs

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim offline deployment docs

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim offline deployment docs

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim support arm arch

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: fox openim support arm arch

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: fox openim support arm arch

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim v3.4 and v3.5 changelog

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add devcontainer.json file

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim v3.4 and v3.5 changelog

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim v3.4 and v3.5 changelog

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* Update util.sh

amend shell get pid command fd on mac.

* feat: Add To start developing OpenIM Docs

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* docs: update openim readme and dov container

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: set openim lint

Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com>

* feat: fix go release scripts

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: fix go release scripts

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* docs(changelog): add CHANGELOG-3.5.0+6.a09200e.md

* docs(changelog): add CHANGELOG-3.5.0+2.e0bd54f.md

* docs(changelog): add CHANGELOG-3.5.0+2.e0bd54f-1-g4ce6a0fa6.md

* feat: set openim lint

Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com>

* docs(changelog): add CHANGELOG-3.5.0+2.e0bd54f-3-g52f9fc209.md

* docs(changelog): add CHANGELOG-3.5.0+2.e0bd54f-4-g87f685b17.md

* docs(changelog): add CHANGELOG-3.5.0.md

* feat: set openim lint

Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com>

* fix: fix scripts functions upload

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: fix scripts functions upload

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* docs(changelog): add CHANGELOG-3.5.0.md

* fix: fix scripts functions upload

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix: fix scripts functions upload

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: set openim lint

Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com>

---------

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
Signed-off-by: Xinwei Xiong(cubxxw) <3293172751nss@gmail.com>
Co-authored-by: mrwenhui <mr.wenhui@gmail.com>
2024-01-12 10:04:06 +00:00
chao bf46412c5a fix: GroupApplicationRejectedNotification not notification apply for userID (#1740)
* fix: GroupApplicationAcceptedNotification

* fix: GroupApplicationAcceptedNotification

* fix: NotificationUserInfoUpdate
2024-01-12 03:49:16 +00:00
Brabem 04c77bff7e fix: fix the mongo search error (#1736)
* fix: improve the GetSortedConversation api

* fix: fix the go.mod

* fix: fix the valiable name

* fix: the FindUser error

* fix: fix the mongo search
2024-01-10 10:59:12 +00:00
Brabem 1c72e46cc9 fix: fix the GetSortedConversationList (#1725)
* fix: improve the GetSortedConversation api

* fix: fix the go.mod

* fix: fix the valiable name
2024-01-10 02:55:55 +00:00
AndrewZuo01 a2a082f681 update usercommand and fix callback (#1681)
* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* update set pin friends

* fix bugs

* fix bugs

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* debug

* Update go.mod

* Update friend.go

* debug

* debug

* debug

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* add pin friend test

* I cannot solve todo in test.sh

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* update user command

* Update go.mod

* fix group notification

* fix group notification

* update openimsdk tools

* update openim server remove duplicate code

* update openim server remove duplicate code

* update user command get

* update user command get

* update response of callback response error

* update black ex

* update join group ex

* update user pb2map

* update go sum

* update go sum

* update updateUserInfoEx

* update updateUserInfoEx

* update updateUserInfoEx add callback functions

* fix dismiss group function

* fix dismiss group function

* fix dismiss group function

* fix dismiss group function

* update pin friend to update friend

* fix go mod

* fix err golangci-lint

* fix UserPb2DBMap

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* update comments, update go.mod check for register username

* fix callback

* fix go.mod

* fix debug

* fix bugs

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* update notification

* fix updateUserInfoEx

* fix updateUserInfoEx

* modify go.mod

* fix updateUserInfoEx

* fix updateUserInfoEx

* fix updateUserInfoEx

* update user command notification

* update user command get all notification

* update user command get all notification

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix type = 0

* fix typing cause callback

* add ex to usercommand

* add ex to usercommand

* update updatefriends

* fix updatefriend map

* fix updatefriend FriendsInfoUpdateNotification

* fix push online and offline user, but why typing trigger callback push?

* fix push online and offline user, but why typing trigger callback push?

* update user command record not found and user access check

* update user command get all user access check

* update go.mod

* fix callback name and place

* upadtae callback test

* fix callback typing

* fix callback typing

* fix callback typing

* fix callback typing

* fix lint on processusercommand

---------

Co-authored-by: Xinwei Xiong <3293172751@qq.com>
2024-01-10 02:27:03 +00:00
Gordon 535ae19f7a fix: group messages sync failed. (#1720)
* fix: add notifications for some notifications.

* fix: modify dismissed group's status.

* fix: Adjust the logic in multiTerminalLoginChecker to prevent onlineUserNum from decreasing below zero, thereby avoiding negative values.

* fix: group messages sync failed.
2024-01-09 06:49:31 +00:00
skiffer-git 3ff588896f update: update readme (#1714)
* update: update readme

* update: update readme

* update: update readme

* update: update readme
2024-01-08 13:40:04 +00:00
Brabem d91a665891 fix: fix some bug (#1710)
* fix: test the getUser api

* fix: fix the go.mod

* fix: fix the go.mod

* fix: fix the go.mod

* fix: fix the addNotificationAccount req

* fix: fix the addnotificationAccount resp

* fix: fix the searchNotificationResp

* fix: fix the go mod

* fix: fix the field of PageFindUser

* Update openimci.yml

* Update openimci.yml

---------

Co-authored-by: Xinwei Xiong <3293172751@qq.com>
2024-01-08 13:38:48 +00:00
chao ceb950a57f feat: send msg at text (#1705) 2024-01-08 07:16:28 +00:00
Xinwei Xiong f27b1e43f5 Enhancements to Script Variables and Logic in OpenIM, Including dig Detection and Mongo Startup Checks (#1696)
* update openim and optimize openim docs and dig check

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim and optimize openim docs and dig check

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim and optimize openim docs and dig check

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* update openim environment and status

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: sava openim cicd

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* feat: add openim mongo logic

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

---------

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
2024-01-07 07:02:59 +00:00
Xinwei Xiong c241f5bea1 Update cla.yml (#1692) 2024-01-06 13:02:47 +00:00
Xinwei Xiong 8aac6c6f81 Fix(main): fix openim config from mongo password env upgrade openim build CICD (#1689)
* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

* fix openim config mongo passwd env

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>

---------

Signed-off-by: Xinwei Xiong (cubxxw) <3293172751nss@gmail.com>
2024-01-05 03:19:40 +00:00
118 changed files with 4660 additions and 5947 deletions
+140
View File
@@ -0,0 +1,140 @@
# OpenIM - OSS Development Container
[![Open in Dev Containers](https://img.shields.io/static/v1?label=Dev%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/openimsdk/open-im-server)
This repository includes configuration for a development container for working with OpenIM - OSS in a local container or using [GitHub Codespaces](https://github.com/features/codespaces).
> **Tip:** The default VNC password is `openIM123`. The VNC server runs on port `5901` and a web client is available on port `11001`, openim-admin on port `11002`.
## Quick start - local
If you already have VS Code and Docker installed, you can click the badge above or [here](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/openimsdk/open-im-server) to get started. Clicking these links will cause VS Code to automatically install the Dev Containers extension if needed, clone the source code into a container volume, and spin up a dev container for use.
1. Install Docker Desktop or Docker for Linux on your local machine. (See [docs](https://aka.ms/vscode-remote/containers/getting-started) for additional details.)
2. **Important**: Docker needs at least **4 Cores and 8 GB of RAM** to run a full build with **9 GB of RAM** being recommended. If you are on macOS, or are using the old Hyper-V engine for Windows, update these values for Docker Desktop by right-clicking on the Docker status bar item and going to **Preferences/Settings > Resources > Advanced**.
> **Note:** The [Resource Monitor](https://marketplace.visualstudio.com/items?itemName=mutantdino.resourcemonitor) extension is included in the container so you can keep an eye on CPU/Memory in the status bar.
3. Install [Visual Studio Code Stable](https://code.visualstudio.com/) or [Insiders](https://code.visualstudio.com/insiders/) and the [Dev Containers](https://aka.ms/vscode-remote/download/containers) extension.
![Image of Dev Containers extension](https://microsoft.github.io/vscode-remote-release/images/dev-containers-extn.png)
> **Note:** The Dev Containers extension requires the Visual Studio Code distribution of OpenIM - OSS. See the [FAQ](https://aka.ms/vscode-remote/faq/license) for details.
4. Press <kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or <kbd>F1</kbd> and select **Dev Containers: Clone Repository in Container Volume...**.
> **Tip:** While you can use your local source tree instead, operations like `yarn install` can be slow on macOS or when using the Hyper-V engine on Windows. We recommend using the WSL filesystem on Windows or the "clone repository in container" approach on Windows and macOS instead since it uses "named volume" rather than the local filesystem.
5. Type `https://github.com/openimsdk/open-im-server` (or a branch or PR URL) in the input box and press <kbd>Enter</kbd>.
6. After the container is running:
1. If you have the `DISPLAY` or `WAYLAND_DISPLAY` environment variables set locally (or in WSL on Windows), desktop apps in the container will be shown in local windows.
2. If these are not set, open a web browser and go to [http://localhost:11001](http://localhost:11001), or use a [VNC Viewer][def] to connect to `localhost:11001` and enter `vscode` as the password. Anything you start in VS Code, or the integrated terminal, will appear here.
Next: **[Try it out!](#try-it)**
## Quick start - GitHub Codespaces
1. From the [openimsdk/open-im-server GitHub repository](https://github.com/openimsdk/open-im-server), click on the **Code** dropdown, select **Open with Codespaces**, and then click on **New codespace**. If prompted, select the **Standard** machine size (which is also the default).
> **Note:** You will not see these options within GitHub if you are not in the Codespaces beta.
2. After the codespace is up and running in your browser, press <kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or <kbd>F1</kbd> and select **Ports: Focus on Ports View**.
3. You should see **VNC web client (11001)** under in the list of ports. Select the line and click on the globe icon to open it in a browser tab.
> **Tip:** If you do not see the port, <kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or <kbd>F1</kbd>, select **Forward a Port** and enter port `11001`.
4. In the new tab, you should see noVNC. Click **Connect** and enter `vscode` as the password.
Anything you start in VS Code, or the integrated terminal, will appear here.
Next: **[Try it out!](#try-it)**
### Using VS Code with GitHub Codespaces
You may see improved VNC responsiveness when accessing a codespace from VS Code client since you can use a [VNC Viewer][def]. Here's how to do it.
1. Install [Visual Studio Code Stable](https://code.visualstudio.com/) or [Insiders](https://code.visualstudio.com/insiders/) and the the [GitHub Codespaces extension](https://marketplace.visualstudio.com/items?itemName=GitHub.codespaces).
> **Note:** The GitHub Codespaces extension requires the Visual Studio Code distribution of OpenIM - OSS.
2. After the VS Code is up and running, press <kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> or <kbd>F1</kbd>, choose **Codespaces: Create New Codespace**, and use the following settings:
- `openimsdk/open-im-server` for the repository.
- Select any branch (e.g. **main**) - you can select a different one later.
- Choose **Standard** (4-core, 8GB) as the size.
3. After you have connected to the codespace, you can use a [VNC Viewer][def] to connect to `localhost:5901` and enter `vscode` as the password.
> **Tip:** You may also need change your VNC client's **Picture Quality** setting to **High** to get a full color desktop.
4. Anything you start in VS Code, or the integrated terminal, will appear here.
Next: **[Try it out!](#try-it)**
## Try it
This container uses the [Fluxbox](http://fluxbox.org/) window manager to keep things lean. **Right-click on the desktop** to see menu options. It works with GNOME and GTK applications, so other tools can be installed if needed.
> **Note:** You can also set the resolution from the command line by typing `set-resolution`.
To start working with OpenIM - OSS, follow these steps:
1. In your local VS Code client, open a terminal (<kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>\`</kbd>) and type the following commands:
```bash
yarn install
bash scripts/code.sh
```
2. After the build is complete, open a web browser or a [VNC Viewer][def] to connect to the desktop environment as described in the quick start and enter `vscode` as the password.
3. You should now see OpenIM - OSS!
Next, let's try debugging.
1. Shut down OpenIM - OSS by clicking the box in the upper right corner of the OpenIM - OSS window through your browser or VNC viewer.
2. Go to your local VS Code client, and use the **Run / Debug** view to launch the **VS Code** configuration. (Typically the default, so you can likely just press <kbd>F5</kbd>).
> **Note:** If launching times out, you can increase the value of `timeout` in the "VS Code", "Attach Main Process", "Attach Extension Host", and "Attach to Shared Process" configurations in [launch.json](../../.vscode/launch.json). However, running `./scripts/code.sh` first will set up Electron which will usually solve timeout issues.
3. After a bit, OpenIM - OSS will appear with the debugger attached!
Enjoy!
### Dotfiles
Dotfiles are files and folders on Unix-like systems starting with `.` that control the configuration of applications and shells on your system. You can store and manage your dotfiles in a repository on GitHub. For advice and tutorials about what to include in your dotfiles repository, see [GitHub does dotfiles](https://dotfiles.github.io/).
Your dotfiles repository might include your shell aliases and preferences, any tools you want to install, or any other codespace personalization you want to make.
You can configure GitHub Codespaces to use dotfiles from any repository you own by selecting that repository in your [personal GitHub Codespaces settings](https://github.com/settings/codespaces).
When you create a new codespace, GitHub clones your selected dotfiles repository to the codespace environment, and looks for one of the following files to set up the environment.
- *install.sh*
- *install*
- *bootstrap.sh*
- *bootstrap*
- *script/bootstrap*
- *setup.sh*
- *setup*
- *script/setup*
If none of these files are found, then any files or folders in your selected dotfiles repository starting with `.` are symlinked to the codespace's `~` or `$HOME` directory.
Any changes to your selected dotfiles repository will apply only to each new codespace, and do not affect any existing codespace.
**Note:** Currently, Codespaces does not support personalizing the User-scoped settings for VS Code with your `dotfiles` repository. You can set default Workspace and Remote [Codespaces] settings for a specific project in the project's repository. For more information, see "[Introduction to dev containers](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/adding-a-dev-container-configuration/introduction-to-dev-containers#creating-a-custom-dev-container-configuration)."
In addition, you can also configure Codespaces secrets on your personal profile page at [github.com/settings/codespaces](https://github.com/settings/codespaces). Development environment secrets are environment variables that are encrypted, and they are accessible to any codespace you create using repositories that have access to these secrets.
### Notes
The container comes with VS Code Insiders installed. To run it from an Integrated Terminal use `VSCODE_IPC_HOOK_CLI= /usr/bin/code-insiders .`.
[def]: https://www.realvnc.com/en/connect/download/viewer/
+72
View File
@@ -0,0 +1,72 @@
{
// Reference Doc: https://code.visualstudio.com/remote/advancedcontainers/overview
"name": "OpenIM Dev Environment",
// Update the container version when you publish dev-container
"build": { "dockerfile": "Dockerfile" },
// Replace with uncommented line below to build your own local copy of the image
// "dockerFile": "../docker/Dockerfile-dev",
"remoteEnv": {
"GO111MODULE": "on",
"GOPROXY": "https://goproxy.cn",
"GOSUMDB": "sum.golang.org",
"GONOPROXY": "github.com/openimsdk",
"GONOSUMDB": "github.com/openimsdk",
"GOPRIVATE": "github.com/openimsdk"
},
"customizations": {
"vscode": {
"extensions": [
"davidanson.vscode-markdownlint",
"golang.go",
"ms-azuretools.vscode-dapr",
"ms-azuretools.vscode-docker",
"ms-kubernetes-tools.vscode-kubernetes-tools"
],
"settings": {
"go.toolsManagement.checkForUpdates": "local",
"go.useLanguageServer": true,
"go.gopath": "/go"
}
}
},
"mounts": [
// Mount docker-in-docker library volume
"type=volume,source=dind-var-lib-docker,target=/var/lib/docker",
// Bind mount docker socket under an alias to support docker-from-docker
"type=bind,source=/var/run/docker.sock,target=/var/run/docker-host.sock",
// Bind mount docker socket under an alias to support docker-from-docker
// "type=bind,source=${env:HOME}${env:USERPROFILE}/.minikube/cache,target=/home/openim/.minikube/cache",
// Uncomment to clone local .kube/config into devcontainer
"type=bind,source=${env:HOME}${env:USERPROFILE}/.kube,target=/home/openim/.kube-localhost"
// Uncomment to additionally clone minikube certs into devcontainer for use with .kube/config
// "type=bind,source=${env:HOME}${env:USERPROFILE}/.minikube,target=/home/openim/.minikube-localhost"
],
// Always run image-defined default command
"overrideCommand": false,
// On Linux, this will prevent new files getting created as root, but you
// may need to update the USER_UID and USER_GID in docker/Dockerfile-dev
// to match your user if not 1000.
// "remoteUser": "openimsdk",
"runArgs": [
// Enable ptrace-based debugging for go
"--cap-add=SYS_PTRACE",
"--security-opt",
"seccomp=unconfined",
// Uncomment to bind to host network for local devcontainer; this is necessary if using the
// bind-mounted /var/run/docker-host.sock directly.
"--net=host",
// Enable docker-in-docker configuration. Comment out if not using for better security.
"--privileged",
// Run the entrypoint defined in container image.
"--init"
],
"workspaceFolder": "/workspaces/openim",
"workspaceMount": "type=bind,source=${localWorkspaceFolder},target=/workspaces/openim"
}
+8 -7
View File
@@ -23,8 +23,6 @@ on:
- "docs/**" - "docs/**"
- "README.md" - "README.md"
- "README_zh-CN.md" - "README_zh-CN.md"
- "**.md"
- "docs/**"
- "CONTRIBUTING.md" - "CONTRIBUTING.md"
pull_request: pull_request:
branches: branches:
@@ -33,8 +31,7 @@ on:
paths-ignore: paths-ignore:
- "README.md" - "README.md"
- "README_zh-CN.md" - "README_zh-CN.md"
- "CONTRIBUTING/**" - "CONTRIBUTING.md"
- "**.md"
- "docs/**" - "docs/**"
env: env:
@@ -70,9 +67,6 @@ jobs:
version: '3.x' # If available, use the latest major version that's compatible version: '3.x' # If available, use the latest major version that's compatible
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
- name: OpenIM Scripts Verification(make verify)
run: sudo make verify
- name: Module Operations - name: Module Operations
run: | run: |
sudo make tidy sudo make tidy
@@ -97,6 +91,13 @@ jobs:
- name: Cleanup Build - name: Cleanup Build
run: sudo make clean run: sudo make clean
- name: Push Changes to Main
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "cicd: robot automated Change"
branch: main
continue-on-error: true
- name: Set Current Directory - name: Set Current Directory
id: set_directory id: set_directory
run: echo "::set-output name=directory::$(pwd)" run: echo "::set-output name=directory::$(pwd)"
+1
View File
@@ -34,6 +34,7 @@ deployments/charts/generated-configs/
### OpenIM Config ### ### OpenIM Config ###
.env .env
config/config.yaml config/config.yaml
config/openim.yaml
config/alertmanager.yml config/alertmanager.yml
config/prometheus.yml config/prometheus.yml
config/email.tmpl config/email.tmpl
+32
View File
@@ -0,0 +1,32 @@
# Version logging for OpenIM
<!-- BEGIN MUNGE: GENERATED_TOC -->
<!-- END MUNGE: GENERATED_TOC -->
<a name="unreleased"></a>
## [Unreleased]
<a name="v3.4.2"></a>
## [v3.4.2] - 2023-12-14
<a name="v3.4.0"></a>
## [v3.4.0] - 2023-11-10
<a name="v3.4.0-rc.1"></a>
## [v3.4.0-rc.1] - 2023-11-09
<a name="v3.4.0-rc.0"></a>
## v3.4.0-rc.0 - 2023-11-09
### Reverts
- update etcd to v3.5.2 ([#206](https://github.com/openimsdk/open-im-server/issues/206))
### Pull Requests
- Merge branch 'tuoyun'
[Unreleased]: https://github.com/openimsdk/open-im-server/compare/v3.4.2...HEAD
[v3.4.2]: https://github.com/openimsdk/open-im-server/compare/v3.4.0...v3.4.2
[v3.4.0]: https://github.com/openimsdk/open-im-server/compare/v3.4.0-rc.1...v3.4.0
[v3.4.0-rc.1]: https://github.com/openimsdk/open-im-server/compare/v3.4.0-rc.0...v3.4.0-rc.1
+76
View File
@@ -0,0 +1,76 @@
# Version logging for OpenIM
<!-- BEGIN MUNGE: GENERATED_TOC -->
<!-- END MUNGE: GENERATED_TOC -->
<a name="unreleased"></a>
## [Unreleased]
<a name="v3.5.1-alpha.1"></a>
## [v3.5.1-alpha.1] - 2024-01-09
<a name="v3.5.0"></a>
## [v3.5.0] - 2024-01-02
<a name="v3.5.1"></a>
## [v3.5.1] - 2024-01-02
<a name="v3.5.1-bate.1"></a>
## [v3.5.1-bate.1] - 2024-01-02
<a name="v3.5.1-rc.0"></a>
## [v3.5.1-rc.0] - 2023-12-30
<a name="v3.5.0-rc.8"></a>
## [v3.5.0-rc.8] - 2023-12-28
<a name="v3.5.0-rc.7"></a>
## [v3.5.0-rc.7] - 2023-12-18
<a name="v3.5.0-rc.6"></a>
## [v3.5.0-rc.6] - 2023-12-15
<a name="v3.5.0-rc.5"></a>
## [v3.5.0-rc.5] - 2023-12-15
<a name="v3.5.0-rc.4"></a>
## [v3.5.0-rc.4] - 2023-12-14
<a name="v3.5.0-rc.3"></a>
## [v3.5.0-rc.3] - 2023-12-14
<a name="v3.5.0-rc.2"></a>
## [v3.5.0-rc.2] - 2023-12-14
<a name="v3.5.0-rc.1"></a>
## [v3.5.0-rc.1] - 2023-12-14
<a name="v3.5.0-rc.0"></a>
## [v3.5.0-rc.0] - 2023-12-14
<a name="v3.5.0-beta.1"></a>
## v3.5.0-beta.1 - 2023-11-29
### Reverts
- update etcd to v3.5.2 ([#206](https://github.com/openimsdk/open-im-server/issues/206))
### Pull Requests
- Merge branch 'tuoyun'
[Unreleased]: https://github.com/openimsdk/open-im-server/compare/v3.5.1-alpha.1...HEAD
[v3.5.1-alpha.1]: https://github.com/openimsdk/open-im-server/compare/v3.5.0...v3.5.1-alpha.1
[v3.5.0]: https://github.com/openimsdk/open-im-server/compare/v3.5.1...v3.5.0
[v3.5.1]: https://github.com/openimsdk/open-im-server/compare/v3.5.1-bate.1...v3.5.1
[v3.5.1-bate.1]: https://github.com/openimsdk/open-im-server/compare/v3.5.1-rc.0...v3.5.1-bate.1
[v3.5.1-rc.0]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.8...v3.5.1-rc.0
[v3.5.0-rc.8]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.7...v3.5.0-rc.8
[v3.5.0-rc.7]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.6...v3.5.0-rc.7
[v3.5.0-rc.6]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.5...v3.5.0-rc.6
[v3.5.0-rc.5]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.4...v3.5.0-rc.5
[v3.5.0-rc.4]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.3...v3.5.0-rc.4
[v3.5.0-rc.3]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.2...v3.5.0-rc.3
[v3.5.0-rc.2]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.1...v3.5.0-rc.2
[v3.5.0-rc.1]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-rc.0...v3.5.0-rc.1
[v3.5.0-rc.0]: https://github.com/openimsdk/open-im-server/compare/v3.5.0-beta.1...v3.5.0-rc.0
+33 -23
View File
@@ -35,52 +35,62 @@
## Ⓜ️ 关于 OpenIM ## Ⓜ️ 关于 OpenIM
OpenIM 不仅仅是一个开源的即时消息组件,它是你的应用程序生态系统的一个不可或缺的部分。查看下面的图表,了解 AppServer、AppClient、OpenIMServer 和 OpenIMSDK 是如何交互的 OpenIM 是一个专门设计用于在应用程序中集成聊天、音视频通话、通知以及AI聊天机器人等通信功能的服务平台。它通过提供一系列强大的API和Webhooks,使开发者可以轻松地在他们的应用中加入这些交互特性。OpenIM 本身并不是一个独立运行的聊天应用,而是作为一个平台,为其他应用提供支持,实现丰富的通信功能。下图展示 AppServer、AppClient、OpenIMServer 和 OpenIMSDK 之间的交互关系来具体说明
![App-OpenIM 关系](./docs/images/oepnim-design.png) ![App-OpenIM 关系](./docs/images/oepnim-design.png)
## 🚀 关于 OpenIMSDK ## 🚀 关于 OpenIMSDK
**OpenIMSDK** 无缝集成到您的应用中,提供丰富、实时的消息体验,无需复杂的 UI 集成。它提供 **OpenIMSDK** 是为 **OpenIMServer** 设计的IM SDK,专为嵌入客户端应用而生。其主要功能及模块如下
+ **本地存储**:用于快速数据检索和消息同步。 + 🌟 主要功能:
+ **监听器回调**:确保实时消息交互性。
+ **API 封装**:简化开发流程。
+ **连接管理**:保证可靠的消息传递。
它使用 Golang 构建,并支持跨平台部署,确保在所有平台上提供一致的消息体验。 - 📦 本地存储
- 🔔 监听器回调
- 🛡️ API封装
- 🌐 连接管理
## 📚 主要模块:
1. 🚀 初始化及登录
2. 👤 用户管理
3. 👫 好友管理
4. 🤖 群组功能
5. 💬 会话处理
它使用 Golang 构建,并支持跨平台部署,确保在所有平台上提供一致的接入体验。
👉 **[探索 GO SDK](https://github.com/openimsdk/openim-sdk-core)** 👉 **[探索 GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 关于 OpenIMServer ## 🌐 关于 OpenIMServer
精心用 Golang 开发的 **OpenIMServer** 通过多重方式确保了卓越的即时消息服务器能力 + **OpenIMServer** 具有以下特点
- 🌐 微服务架构:支持集群模式,包括网关(gateway)和多个rpc服务。
+ **模块组成**:它由多个模块组成,例如网关和多个 RPC 服务,提供一个多功能的消息环境 - 🚀 部署方式多样:支持源代码、kubernetes或docker部署
+ **微服务架构**:支持集群模式,确保出色的性能和可伸缩性,以有效管理各个实例间的通信。 - 海量用户支持:十万超级大群,千万用户,及百亿消息
+ **多样的部署选项**:适应你的操作偏好,通过源代码、Kubernetes 或 Docker 提供部署选项。
### 增强的业务功能: ### 增强的业务功能:
+ **REST API**OpenIMServer 为业务系统提供 REST API,旨在通过后接口为您的操作提供附加功能,如群组创建和消息推送 + **REST API**OpenIMServer 提供REST API供业务系统使用,旨在赋予业务更多功能,例如通过后接口建立群组、发送推送消息等
+ **回调**:为了扩展其在各种业务形式中的实用性,OpenIMServer 提供了回调能力。即,在事件发生之前或之后,向业务服务器发送请求,如发送消息,丰富通信过程中的交互和数据交换流 + **Webhooks**OpenIMServer提供了回调能力以扩展更多的业务形态,所谓回调,即OpenIMServer会在某一事件发生之前或之后,向业务服务器发送请求,如发送消息之前或之后的回调
👉 **[了解更多](https://doc.rentsoft.cn/guides/introduction/product)** 👉 **[了解更多](https://docs.openim.io/guides/introduction/product)**
## :rocket: 快速开始 ## :rocket: 快速开始
你只需要一个简单的命令,就可以快速学习 OpenIM 的工程解决方案 在线体验iOS/Android/H5/PC/Web
``` 👉 **[OpenIM online demo](https://www.openim.io/zh/commercial)**
bashCopy code
$ make demo
```
🤲 为了方便用户体验,我们提供了多种部署解决方案,您可以根据下面的列表选择自己的部署方法: 🤲 为了方便用户体验,我们提供了多种部署解决方案,您可以根据下面的列表选择自己的部署方法:
+ **[源代码部署指南](https://doc.rentsoft.cn/guides/gettingStarted/imSourceCodeDeployment)** + **[源代码部署指南](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
+ **[Docker 部署指南](https://doc.rentsoft.cn/guides/gettingStarted/dockerCompose)** + **[Docker 部署指南](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
+ **[Kubernetes 部署指南](https://github.com/openimsdk/open-im-server/tree/main/deployments)** + **[Kubernetes 部署指南](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
## :hammer_and_wrench: 开始开发 OpenIM ## :hammer_and_wrench: 开始开发 OpenIM
+31 -151
View File
@@ -25,180 +25,58 @@
</p> </p>
## Ⓜ️ About OpenIM ## Ⓜ️ About OpenIM
OpenIM isn't just an open-source instant messaging component, it's an integral part of your application ecosystem. Check out this diagram to understand how AppServer, AppClient, OpenIMServer, and OpenIMSDK interact. OpenIM is a service platform specifically designed for integrating chat, audio-video calls, notifications, and AI chatbots into applications. It provides a range of powerful APIs and Webhooks, enabling developers to easily incorporate these interactive features into their applications. OpenIM is not a standalone chat application, but rather serves as a platform to support other applications in achieving rich communication functionalities. The following diagram illustrates the interaction between AppServer, AppClient, OpenIMServer, and OpenIMSDK to explain in detail.
![App-OpenIM Relationship](./docs/images/oepnim-design.png) ![App-OpenIM Relationship](./docs/images/oepnim-design.png)
## 🚀 About OpenIMSDK ## 🚀 About OpenIMSDK
**OpenIMSDK** seamlessly integrates into your application, delivering a rich, real-time messaging experience without requiring intricate UI integration. It provides: **OpenIMSDK** is an IM SDK designed for **OpenIMServer**, created specifically for embedding in client applications. Its main features and modules are as follows:
+ **Local Storage**: For quick data retrieval and message synchronization. + 🌟 Main Features:
+ **Listener Callbacks**: Ensuring real-time message interactivity.
+ **API Encapsulation**: Streamlining development processes.
+ **Connection Management**: Guaranteeing reliable message delivery.
It's crafted in Golang and supports cross-platform deployment, ensuring a coherent messaging experience across all platforms. - 📦 Local storage
- 🔔 Listener callbacks
- 🛡️ API wrapping
- 🌐 Connection management
## 📚 Main Modules:
1. 🚀 Initialization and Login
2. 👤 User Management
3. 👫 Friend Management
4. 🤖 Group Functions
5. 💬 Conversation Handling
It is built using Golang and supports cross-platform deployment, ensuring a consistent access experience across all platforms.
👉 **[Explore GO SDK](https://github.com/openimsdk/openim-sdk-core)** 👉 **[Explore GO SDK](https://github.com/openimsdk/openim-sdk-core)**
## 🌐 About OpenIMServer ## 🌐 About OpenIMServer
**OpenIMServer**, meticulously developed in Golang, ensures a stellar instant messaging server capability with a multifold approach: + **OpenIMServer** has the following characteristics:
- 🌐 Microservice architecture: Supports cluster mode, including a gateway and multiple rpc services.
- 🚀 Diverse deployment methods: Supports deployment via source code, Kubernetes, or Docker.
- Support for massive user base: Super large groups with hundreds of thousands of users, tens of millions of users, and billions of messages.
+ **Modular Composition**: It's comprised of several modules, such as the gateway and multiple RPC services, offering a versatile messaging environment. ### Enhanced Business Functionality:
+ **Microservices Architecture**: Supporting cluster modes, it assures outstanding performance and scalability to manage communication effectively across various instances.
+ **Diverse Deployment Options**: Adapts to your operational preferences, offering deployment via source code, Kubernetes, or Docker.
### Enhanced Business Functionalities: + **REST API**: OpenIMServer offers REST APIs for business systems, aimed at empowering businesses with more functionalities, such as creating groups and sending push messages through backend interfaces.
+ **Webhooks**: OpenIMServer provides callback capabilities to extend more business forms. A callback means that OpenIMServer sends a request to the business server before or after a certain event, like callbacks before or after sending a message.
+ **REST API**: OpenIMServer provides REST API for business systems, aiming to empower your operations with additional functionalities like group creation and message push via backend interfaces.
+ **Callbacks**: To expand its utility across varied business forms, OpenIMServer offers callback capabilities. That is, it sends a request to the business server before or after an event occurs, such as sending a message, enriching the interaction and data exchange flow in the communication processes.
👉 **[Learn More](https://docs.openim.io/guides/introduction/product)**
<!--
## :star2: Why OpenIM
**🔍 Function screenshot display**
<div align="center">
| 💻🔄📱 Multi Terminal Synchronization 🔄🖥️ | 📅⚡ Efficient Meetings 🚀💼 |
| :----------------------------------------------------------: | :---------------------------------------------------------: |
| ![multiple-message](./assets/demo/multi-terminal-synchronization.png) | ![efficient-meetings](./assets/demo/efficient-meetings.png) |
| 📲🔄 **One-to-one and Group Chats** 👥🗣️ | 🎁💻 **Special Features - Custom Messages** ✉️🎨|
| ![group-chat](./assets/demo/group-chat.png) | ![special-function](./assets/demo/special-function.png) |
</div>
**OpenIM** offers a powerful and reliable instant messaging platform, ensuring versatile communication across multiple platforms with the following key features:
**Versatile Messaging:** Support for text, images, emojis, voice, video, and more, alongside one-on-one and multi-person audio/video calls.
**Robust Chat Capabilities:** Including roles (application administrator, group owner, etc.) and features like muting, group announcements, and dynamic message loading.
**Unique Interaction Features:** Offering read-and-burn private chats and a message editing function to broaden social scenarios.
**Open Source:** The code of OpenIM is open source and aims to build a leading global IM open source community. [GitHub Repository](https://github.com/OpenIMSDK)
**Extensibility:** Implemented in Golang, OpenIM introduces an "everything is a message" communication model, simplifying custom messages and feature extension.
**High Performance:** Supports a hierarchical governance architecture tested and abstracts the storage model of various message types.
**Full Platform Support:** Native support for iOS, Android, Flutter, uni-app, ReactNative, Electron, and Web.
-->
👉 **[Learn more](https://docs.openim.io/guides/introduction/product)**
## :rocket: Quick Start ## :rocket: Quick Start
We support many platforms. Here are the addresses for quick experience on the web side 🤲 To facilitate user experience, we offer various deployment solutions. You can choose your deployment method from the list below:
👉 **[OpenIM online web demo](https://web-enterprise.rentsoft.cn/)**
You can quickly learn OpenIM engineering solutions, all it takes is one simple command:
```bash
$ make demo
```
🤲 In order to facilitate the user experience, we have provided a variety of deployment solutions, you can choose your own deployment method according to the list below:
<!--
<details> <summary>Deploying with Docker Compose</summary>
It is recommended to use Docker Compose for deployment, which can easily and quickly deploy the entire OpenIM service on a single node
+ [https://github.com/openimsdk/openim-docker](https://github.com/openimsdk/openim-docker)
> **Note**
>
> If you don't know OpenIM's versioning policy, 📚Read our release policy: https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/version.md
</details>
<details> <summary>Compile from Source</summary>
Ur need `Go 1.20` or higher version, and `make`.
```bash
go version && make --version || echo "Error: One of the commands failed."
```
Version Details: https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/version.md
You can get the version number from the command below or from [github releases](https://github.com/openimsdk/open-im-server/tags).
```bash
$ curl --silent "https://api.github.com/repos/openimsdk/open-im-server/releases" | jq -r '.[].tag_name'
```
We have our own version management policy, if you are interested in our version management, I recommend reading [📚 OpenIM Version](https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/version.md), We recommend using stable versions such as `v3.3.0` and `v3.2.0` whenever possible. `v3.1.1-alpha.3` as well as `v3.3.0-beta.0` and `v3.2.0-rc.0` are pre-release or beta versions and are not recommended.
Set `OPENIM_VERSION` environment variables for the latest `OPENIM_VERSION` number, or replace the `OPENIM_VERSION` for you to install the OpenIM-Server `OPENIM_VERSION`:
```bash
$ OPENIM_VERSION=`curl -s https://api.github.com/repos/openimsdk/open-im-server/releases/latest | grep -oE '"tag_name": "[^"]+"' | head -n1 | cut -d'"' -f4`
# OPENIM_VERSION=v3.3.0
```
Deploy basic components at the click of a command:
```bash
# install openim dependency
$ git clone https://github.com/openimsdk/open-im-server openim/openim-server && export openim=$(pwd)/openim/openim-server && cd $openim/openim-server && git checkout $OPENIM_VERSION
$ make init && docker compose up -d && make start && make check
```
> `make help` to help you see the instructions supported by OpenIM.
You can use the `make help-all` see OpenIM in action.
</details>
<details> <summary>Component Configuration Instructions</summary>
Read: Configuration center documenthttps://github.com/openimsdk/open-im-server/blob/main/docs/contrib/environment.md
</details>
<details> <summary>Deployed with kubernetes</summary>
+ https://github.com/openimsdk/open-im-server/blob/main/deployments/README.md
</details>
-->
+ **[Source Code Deployment Guide](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)** + **[Source Code Deployment Guide](https://docs.openim.io/guides/gettingStarted/imSourceCodeDeployment)**
+ **[Production deployment of Linux systems](https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/install-openim-linux-system.md)**
+ **[Docker Deployment Guide](https://docs.openim.io/guides/gettingStarted/dockerCompose)** + **[Docker Deployment Guide](https://docs.openim.io/guides/gettingStarted/dockerCompose)**
+ **[Kubernetes Deployment Guide](https://github.com/openimsdk/open-im-server/tree/main/deployments)** + **[Kubernetes Deployment Guide](https://docs.openim.io/guides/gettingStarted/k8s-deployment)**
<!-- ## :hammer_and_wrench: To Start Developing OpenIM
## :link: OpenIM and your application
OpenIM isn't just an open-source instant messaging component, it's an integral part of your application ecosystem. Check out this diagram to understand how AppServer, AppClient, OpenIMServer, and OpenIMSDK interact.
![App-OpenIM Relationship](./docs/images/oepnim-design.png)
## :building_construction: Overall Architecture
Delve into the heart of Open-IM-Server's functionality with our architecture diagram.
![Overall Architecture](./docs/images/Architecture.jpg) -->
## :hammer_and_wrench: To start developing OpenIM
[![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server) [![Open in Dev Container](https://img.shields.io/static/v1?label=Dev%20Container&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/github/openimsdk/open-im-server)
@@ -236,6 +114,8 @@ Before you start, please make sure your changes are in demand. The best for that
- [OpenIM Script Utilities](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/util-scripts.md) - [OpenIM Script Utilities](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/util-scripts.md)
- [OpenIM Versioning](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/version.md) - [OpenIM Versioning](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/version.md)
- [Manage backend and monitor deployment](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/prometheus-grafana.md) - [Manage backend and monitor deployment](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/prometheus-grafana.md)
- [Mac Developer Deployment Guide for OpenIM](https://github.com/openimsdk/open-im-server/tree/main/docs/contrib/mac-developer-deployment-guide.md)
## :busts_in_silhouette: Community ## :busts_in_silhouette: Community
@@ -252,7 +132,7 @@ Our conference is in the [OpenIM Slack](https://join.slack.com/t/openimsdk/share
We take notes of each [biweekly meeting](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) in [GitHub discussions](https://github.com/openimsdk/open-im-server/discussions/categories/meeting), Our historical meeting notes, as well as replays of the meetings are available at [Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing). We take notes of each [biweekly meeting](https://github.com/orgs/OpenIMSDK/discussions/categories/meeting) in [GitHub discussions](https://github.com/openimsdk/open-im-server/discussions/categories/meeting), Our historical meeting notes, as well as replays of the meetings are available at [Google Docs :bookmark_tabs:](https://docs.google.com/document/d/1nx8MDpuG74NASx081JcCpxPgDITNTpIIos0DS6Vr9GU/edit?usp=sharing).
## :eyes: Who are using OpenIM ## :eyes: Who Are Using OpenIM
Check out our [user case studies](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) page for a list of the project users. Don't hesitate to leave a [📝comment](https://github.com/openimsdk/open-im-server/issues/379) and share your use case. Check out our [user case studies](https://github.com/OpenIMSDK/community/blob/main/ADOPTERS.md) page for a list of the project users. Don't hesitate to leave a [📝comment](https://github.com/openimsdk/open-im-server/issues/379) and share your use case.
+1 -1
View File
@@ -25,7 +25,7 @@ assets/
## Copyright Notice: ## Copyright Notice:
The OpenIM logo, including its variations and animated versions, displayed in this repository [OpenIM](https://github.com/OpenIMSDK/openim) under the `/assets/logo` and `/assets/logo-gif` directories, are protected by copyright laws. The OpenIM logo, including its variations and animated versions, displayed in this repository [OpenIM](https://github.com/openimsdk/open-im-server) under the `/assets/logo` and `/assets/logo-gif` directories, are protected by copyright laws.
The logo design is credited to @Xx(席欣). The logo design is credited to @Xx(席欣).
+11
View File
@@ -0,0 +1,11 @@
# Official Colors
The openim logo has an official blue color. When reproducing the logo, please use the official color, when possible.
## Pantone
When possible, the Pantone color is preferred for print material. The official Pantone color is *285C*.
## RGB
When used digitally, the official RGB color code is *#326CE5*.
@@ -1,45 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# OpenIM base image: https://github.com/openim-sigs/openim-base-image
# Set go mod installation source and proxy
FROM golang:1.20 AS builder
ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct
WORKDIR /openim/openim-server
ENV GO111MODULE=$GO111MODULE
ENV GOPROXY=$GOPROXY
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN make build BINS=openim-rpc-encryption
RUN cp /openim/openim-server/_output/bin/platforms/$(go env GOOS)/$(go env GOARCH)/openim-rpc-encryption /usr/bin/openim-rpc-encryption
# FROM ghcr.io/openim-sigs/openim-bash-image:latest
FROM ghcr.io/openim-sigs/openim-bash-image:latest
WORKDIR /openim/openim-server
COPY --from=builder /usr/bin/openim-rpc-encryption ./bin/openim-rpc-encryption
ENTRYPOINT ["./bin/openim-rpc-encryption"]
@@ -1,45 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# OpenIM base image: https://github.com/openim-sigs/openim-base-image
# Set go mod installation source and proxy
FROM golang:1.20 AS builder
ARG GO111MODULE=on
ARG GOPROXY=https://goproxy.cn,direct
WORKDIR /openim/openim-server
ENV GO111MODULE=$GO111MODULE
ENV GOPROXY=$GOPROXY
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN make build BINS=openim-rpc-extend-msg
RUN cp /openim/openim-server/_output/bin/platforms/$(go env GOOS)/$(go env GOARCH)/openim-rpc-extend-msg /usr/bin/openim-rpc-extend-msg
# FROM ghcr.io/openim-sigs/openim-bash-image:latest
FROM ghcr.io/openim-sigs/openim-bash-image:latest
WORKDIR /openim/openim-server
COPY --from=builder /usr/bin/openim-rpc-extend-msg ./bin/openim-rpc-extend-msg
ENTRYPOINT ["./bin/openim-rpc-extend-msg"]
+2 -2
View File
@@ -35,7 +35,7 @@ import (
"github.com/openimsdk/open-im-server/v3/pkg/common/config" "github.com/openimsdk/open-im-server/v3/pkg/common/config"
"github.com/openimsdk/open-im-server/v3/pkg/common/db/cache" "github.com/openimsdk/open-im-server/v3/pkg/common/db/cache"
kdisc "github.com/openimsdk/open-im-server/v3/pkg/common/discoveryregister" kdisc "github.com/openimsdk/open-im-server/v3/pkg/common/discoveryregister"
ginProm "github.com/openimsdk/open-im-server/v3/pkg/common/ginprometheus" ginprom "github.com/openimsdk/open-im-server/v3/pkg/common/ginprometheus"
"github.com/openimsdk/open-im-server/v3/pkg/common/prommetrics" "github.com/openimsdk/open-im-server/v3/pkg/common/prommetrics"
) )
@@ -88,7 +88,7 @@ func run(port int, proPort int) error {
log.ZInfo(context.Background(), "api register public config to discov success") log.ZInfo(context.Background(), "api register public config to discov success")
router := api.NewGinRouter(client, rdb) router := api.NewGinRouter(client, rdb)
if config.Config.Prometheus.Enable { if config.Config.Prometheus.Enable {
p := ginProm.NewPrometheus("app", prommetrics.GetGinCusMetrics("Api")) p := ginprom.NewPrometheus("app", prommetrics.GetGinCusMetrics("Api"))
p.SetListenAddress(fmt.Sprintf(":%d", proPort)) p.SetListenAddress(fmt.Sprintf(":%d", proPort))
p.Use(router) p.Use(router)
} }
@@ -1,47 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###################### AlertManager Configuration ######################
# AlertManager configuration using environment variables
#
# Resolve timeout
# SMTP configuration for sending alerts
# Templates for email notifications
# Routing configurations for alerts
# Receiver configurations
global:
resolve_timeout: 5m
smtp_from: alert@openim.io
smtp_smarthost: smtp.163.com:465
smtp_auth_username: alert@openim.io
smtp_auth_password: YOURAUTHPASSWORD
smtp_require_tls: false
smtp_hello: xxx监控告警
templates:
- /etc/alertmanager/email.tmpl
route:
group_by: ['alertname']
group_wait: 5s
group_interval: 5s
repeat_interval: 5m
receiver: email
receivers:
- name: email
email_configs:
- to: 'alert@example.com'
html: '{{ template "email.to.html" . }}'
headers: { Subject: "[OPENIM-SERVER]Alarm" }
send_resolved: true
-521
View File
@@ -1,521 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------
# TODO: This config file is the template file
# --| source: deployments/templates/openim.yaml
# --| env: scripts/install/environment
# --| target: config/config.yaml
# -----------------------------------------------------------------
envs:
discovery: zookeeper
###################### Zookeeper ######################
# Zookeeper configuration
# It's not recommended to modify the schema
#
# Zookeeper address
# Zookeeper username
# Zookeeper password
zookeeper:
schema: openim
address: [ 172.28.0.1:12181 ]
username: ''
password: ''
###################### Mongo ######################
# MongoDB configuration
# If uri is not empty, it will be used directly for the MongoDB connection.
# This is a complete MongoDB URI string.
# Example: mongodb://user:password@host1:port1,host2:port2/dbname?options
mongo:
uri: ''
# List of MongoDB server addresses.
# Used for constructing the MongoDB URI if 'uri' above is empty.
# For a standalone setup, specify the address of the single server.
# For a sharded cluster, specify the addresses of the Mongos servers.
# Example: [ '172.28.0.1:37017', '172.28.0.2:37017' ]
# Default MongoDB database name
# Maximum connection pool size
address: [ 172.28.0.1:37017 ]
database: openIM_v3
username: root
password: openIM123
maxPoolSize: 100
###################### Redis configuration information ######################
# Redis configuration
#
# Username is required only for Redis version 6.0+
redis:
address: [ 172.28.0.1:16379 ]
username: ''
password: openIM123
###################### Kafka configuration information ######################
# Kafka configuration
#
# Kafka username
# Kafka password
# It's not recommended to modify this topic name
# Consumer group ID, it's not recommended to modify
kafka:
username: ''
password: ''
addr: [ 172.28.0.1:19094 ]
latestMsgToRedis:
topic: "latestMsgToRedis"
offlineMsgToMongo:
topic: "offlineMsgToMongoMysql"
msgToPush:
topic: "msgToPush"
consumerGroupID:
msgToRedis: redis
msgToMongo: mongo
msgToMySql: mysql
msgToPush: push
###################### RPC configuration information ######################
# RPC configuration
#
# IP address to register with zookeeper when starting RPC, the IP and corresponding rpcPort should be accessible by api/gateway
# Default listen IP is 0.0.0.0
rpc:
registerIP: ''
listenIP: 0.0.0.0
###################### API configuration information ######################
# API configuration
#
# API service port
# Default listen IP is 0.0.0.0
api:
openImApiPort: [ 10002 ]
listenIP: 0.0.0.0
###################### Object configuration information ######################
# Object storage configuration
#
# Use minio for object storage
# API URL should be accessible by the app
# It's not recommended to modify the bucket name
# Endpoint should be accessible by the app
# Session token
# Configuration for Tencent COS
# Configuration for Aliyun OSS
# apiURL is the address of the api, the access address of the app, use s3 must be configured
# minio.endpoint can be configured as an intranet address,
# minio.signEndpoint is minio public network address
object:
enable: "minio"
apiURL: "http://14.155.64.202:10002"
minio:
bucket: "openim"
endpoint: "http://172.28.0.1:10005"
accessKeyID: "root"
secretAccessKey: "openIM123"
sessionToken: ''
signEndpoint: "http://14.155.64.202:10005"
publicRead: false
cos:
bucketURL: https://temp-1252357374.cos.ap-chengdu.myqcloud.com
secretID: ''
secretKey: ''
sessionToken: ''
publicRead: false
oss:
endpoint: "https://oss-cn-chengdu.aliyuncs.com"
bucket: "demo-9999999"
bucketURL: "https://demo-9999999.oss-cn-chengdu.aliyuncs.com"
accessKeyID: ''
accessKeySecret: ''
sessionToken: ''
publicRead: false
kodo:
endpoint: "http://s3.cn-east-1.qiniucs.com"
bucket: "demo-9999999"
bucketURL: "http://your.domain.com"
accessKeyID: ''
accessKeySecret: ''
sessionToken: ''
publicRead: false
###################### RPC Port Configuration ######################
# RPC service ports
# These ports are passed into the program by the script and are not recommended to modify
# For launching multiple programs, just fill in multiple ports separated by commas
# For example, [10110, 10111]
rpcPort:
openImUserPort: [ 10110 ]
openImFriendPort: [ 10120 ]
openImMessagePort: [ 10130 ]
openImGroupPort: [ 10150 ]
openImAuthPort: [ 10160 ]
openImPushPort: [ 10170 ]
openImConversationPort: [ 10180 ]
openImThirdPort: [ 10190 ]
###################### RPC Register Name Configuration ######################
# RPC service names for registration, it's not recommended to modify these
rpcRegisterName:
openImUserName: User
openImFriendName: Friend
openImMsgName: Msg
openImPushName: Push
openImMessageGatewayName: MessageGateway
openImGroupName: Group
openImAuthName: Auth
openImConversationName: Conversation
openImThirdName: Third
###################### Log Configuration ######################
# Log configuration
#
# Storage directory
# Log rotation time
# Maximum number of logs to retain
# Log level, 6 means all levels
# Whether to output to stdout
# Whether to output in json format
# Whether to include stack trace in logs
log:
storageLocation: /data/workspaces/open-im-server/logs/
rotationTime: 24
remainRotationCount: 2
remainLogLevel: 6
isStdout: false
isJson: false
withStack: false
###################### Variables definition ######################
# Long connection server configuration
#
# Websocket port for msg_gateway
# Maximum number of websocket connections
# Maximum length of websocket request package
# Websocket connection handshake timeout
longConnSvr:
openImWsPort: [ 10001 ]
websocketMaxConnNum: 100000
openImMessageGatewayPort: [ 10140 ]
websocketMaxMsgLen: 4096
websocketTimeout: 10
# Push notification service configuration
#
# Use GeTui for push notifications
# GeTui offline push configuration
# FCM offline push configuration
# Account file, place it in the config directory
# JPush configuration, modify these after applying in JPush backend
push:
enable: getui
geTui:
pushUrl: "https://restapi.getui.com/v2/$appId"
masterSecret: ''
appKey: ''
intent: ''
channelID: ''
channelName: ''
fcm:
serviceAccount: "x.json"
jpns:
appKey: ''
masterSecret: ''
pushUrl: ''
pushIntent: ''
# App manager configuration
#
# Built-in app manager user IDs
# Built-in app manager nicknames
manager:
userID: [ "openIM123456", "openIM654321", "openIMAdmin" ]
nickname: [ "system1", "system2", "system3" ]
# Multi-platform login policy
# For each platform(Android, iOS, Windows, Mac, web), only one can be online at a time
multiLoginPolicy: 1
# Whether to store messages in MySQL, messages in MySQL are only used for management background
chatPersistenceMysql: true
# Message cache timeout in seconds, it's not recommended to modify
msgCacheTimeout: 86400
# Whether to enable read receipts for group chat
groupMessageHasReadReceiptEnable: true
# Whether to enable read receipts for single chat
singleMessageHasReadReceiptEnable: true
# MongoDB offline message retention period in days
retainChatRecords: 365
# Schedule to clear expired messages(older than retainChatRecords days) in MongoDB every Wednesday at 2am
# This deletion is just for cleaning up disk usage according to previous configuration retainChatRecords, no notification will be sent
chatRecordsClearTime: "0 2 * * 3"
# Schedule to auto delete messages every day at 2am
# This deletion is for messages that have been retained for more than msg_destruct_time (seconds) in the conversation field
msgDestructTime: "0 2 * * *"
# Secret key
secret: openIM123
# Token policy
#
# Token expiration period in days
tokenPolicy:
expire: 90
# Message verification policy
#
# Whether to verify friendship when sending messages
messageVerify:
friendVerify: false
# iOS push notification configuration
#
# iOS push notification sound
# Whether to count badge
# Whether it's production environment
iosPush:
pushSound: "xxx"
badgeCount: true
production: false
###################### Third-party service configuration ######################
# Callback configuration
#
# Callback URL
# Whether to enable this callback event
# Timeout in seconds
# Whether to continue execution if callback fails
callback:
url: ""
beforeSendSingleMsg:
enable: false
timeout: 5
failedContinue: true
beforeUpdateUserInfoEx:
enable: false
timeout: 5
failedContinue: true
afterUpdateUserInfoEx:
enable: false
timeout: 5
failedContinue: true
afterSendSingleMsg:
enable: false
timeout: 5
failedContinue: true
beforeSendGroupMsg:
enable: false
timeout: 5
failedContinue: true
afterSendGroupMsg:
enable: false
timeout: 5
failedContinue: true
msgModify:
enable: false
timeout: 5
failedContinue: true
userOnline:
enable: false
timeout: 5
failedContinue: true
userOffline:
enable: false
timeout: 5
failedContinue: true
userKickOff:
enable: false
timeout: 5
failedContinue: true
offlinePush:
enable: false
timeout: 5
failedContinue: true
onlinePush:
enable: false
timeout: 5
failedContinue: true
superGroupOnlinePush:
enable: false
timeout: 5
failedContinue: true
beforeAddFriend:
enable: false
timeout: 5
failedContinue: true
beforeUpdateUserInfo:
enable: false
timeout: 5
failedContinue: true
beforeCreateGroup:
enable: false
timeout: 5
failedContinue: true
afterCreateGroup:
enable: false
timeout: 5
failedContinue: true
beforeMemberJoinGroup:
enable: false
timeout: 5
failedContinue: true
beforeSetGroupMemberInfo:
enable: false
timeout: 5
failedContinue: true
afterSetGroupMemberInfo:
enable: false
timeout: 5
failedContinue: true
setMessageReactionExtensions:
enable: false
timeout: 5
failedContinue: true
quitGroup:
enable: false
timeout: 5
failedContinue: true
killGroupMember:
enable: false
timeout: 5
failedContinue: true
dismissGroup:
enable: false
timeout: 5
failedContinue: true
joinGroup:
enable: false
timeout: 5
failedContinue: true
groupMsgRead:
enable: false
timeout: 5
failedContinue: true
singleMsgRead:
enable: false
timeout: 5
failedContinue: true
updateUserInfo:
enable: false
timeout: 5
failedContinue: true
beforeUserRegister:
enable: false
timeout: 5
failedContinue: true
afterUserRegister:
enable: false
timeout: 5
failedContinue: true
transferGroupOwner:
enable: false
timeout: 5
failedContinue: true
beforeSetFriendRemark:
enable: false
timeout: 5
failedContinue: true
afterSetFriendRemark:
enable: false
timeout: 5
failedContinue: true
afterGroupMsgRead:
enable: false
timeout: 5
failedContinue: true
afterGroupMsgRevoke:
enable: false
timeout: 5
failedContinue: true
afterJoinGroup:
enable: false
timeout: 5
failedContinue: true
beforeInviteUserToGroup:
enable: false
timeout: 5
failedContinue: true
joinGroupAfter:
enable: false
timeout: 5
failedContinue: true
setGroupInfoAfter:
enable: false
timeout: 5
failedContinue: true
setGroupInfoBefore:
enable: false
timeout: 5
failedContinue: true
revokeMsgAfter:
enable: false
timeout: 5
failedContinue: true
addBlackBefore:
enable: false
timeout: 5
failedContinue: true
addFriendAfter:
enable: false
timeout: 5
failedContinue: true
addFriendAgreeBefore:
enable: false
timeout: 5
failedContinue: true
deleteFriendAfter:
enable: false
timeout: 5
failedContinue: true
importFriendsBefore:
enable: false
timeout: 5
failedContinue: true
importFriendsAfter:
enable: false
timeout: 5
failedContinue: true
removeBlackAfter:
enable: false
timeout: 5
failedContinue: true
###################### Prometheus ######################
# Prometheus configuration for various services
# The number of Prometheus ports per service needs to correspond to rpcPort
# The number of ports needs to be consistent with msg_transfer_service_num in script/path_info.sh
prometheus:
enable: false
grafanaUrl: 172.28.0.1:13000
apiPrometheusPort: [20100]
userPrometheusPort: [ 20110 ]
friendPrometheusPort: [ 20120 ]
messagePrometheusPort: [ 20130 ]
messageGatewayPrometheusPort: [ 20140 ]
groupPrometheusPort: [ 20150 ]
authPrometheusPort: [ 20160 ]
pushPrometheusPort: [ 20170 ]
conversationPrometheusPort: [ 20230 ]
rtcPrometheusPort: [ 21300 ]
thirdPrometheusPort: [ 21301 ]
messageTransferPrometheusPort: [ 21400, 21401, 21402, 21403 ] # List of ports
-16
View File
@@ -1,16 +0,0 @@
{{ define "email.to.html" }}
{{ range .Alerts }}
<!-- Begin of OpenIM Alert -->
<div style="border:1px solid #ccc; padding:10px; margin-bottom:10px;">
<h3>OpenIM Alert</h3>
<p><strong>Alert Program:</strong> Prometheus Alert</p>
<p><strong>Severity Level:</strong> {{ .Labels.severity }}</p>
<p><strong>Alert Type:</strong> {{ .Labels.alertname }}</p>
<p><strong>Affected Host:</strong> {{ .Labels.instance }}</p>
<p><strong>Affected Service:</strong> {{ .Labels.job }}</p>
<p><strong>Alert Subject:</strong> {{ .Annotations.summary }}</p>
<p><strong>Trigger Time:</strong> {{ .StartsAt.Format "2006-01-02 15:04:05" }}</p>
</div>
<!-- End of OpenIM Alert -->
{{ end }}
{{ end }}
-260
View File
@@ -1,260 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ======================================
# ========= Basic Configuration ========
# ======================================
# The user for authentication or system operations.
# Default: OPENIM_USER=root
USER=root
# Password associated with the specified user for authentication.
# Default: PASSWORD=openIM123
PASSWORD=openIM123
# Base URL for the application programming interface (API).
# Default: API_URL=http://172.28.0.1:10002
API_URL=http://14.155.64.202:10002
# Directory path for storing data files or related information.
# Default: DATA_DIR=./
DATA_DIR=/data/workspaces/open-im-server
# Choose the appropriate image address, the default is GITHUB image,
# you can choose docker hub, for Chinese users can choose Ali Cloud
# export IMAGE_REGISTRY="ghcr.io/openimsdk"
# export IMAGE_REGISTRY="openim"
# export IMAGE_REGISTRY="registry.cn-hangzhou.aliyuncs.com/openimsdk"
IMAGE_REGISTRY=ghcr.io/openimsdk
# ======================================
# ========= Network Configuration ======
# ======================================
# Subnet for the Docker network.
# Default: DOCKER_BRIDGE_SUBNET=172.28.0.0/16
DOCKER_BRIDGE_SUBNET=172.28.0.0/16
# Gateway for the Docker network.
# Default: DOCKER_BRIDGE_GATEWAY=172.28.0.1
DOCKER_BRIDGE_GATEWAY=172.28.0.1
MONGO_NETWORK_ADDRESS=172.28.0.2
REDIS_NETWORK_ADDRESS=172.28.0.3
KAFKA_NETWORK_ADDRESS=172.28.0.4
ZOOKEEPER_NETWORK_ADDRESS=172.28.0.5
MINIO_NETWORK_ADDRESS=172.28.0.6
OPENIM_WEB_NETWORK_ADDRESS=172.28.0.7
OPENIM_SERVER_NETWORK_ADDRESS=172.28.0.8
OPENIM_CHAT_NETWORK_ADDRESS=172.28.0.9
PROMETHEUS_NETWORK_ADDRESS=172.28.0.10
GRAFANA_NETWORK_ADDRESS=172.28.0.11
NODE_EXPORTER_NETWORK_ADDRESS=172.28.0.12
OPENIM_ADMIN_FRONT_NETWORK_ADDRESS=172.28.0.13
ALERT_MANAGER_NETWORK_ADDRESS=172.28.0.14
# ===============================================
# = Component Extension Configuration =
# ===============================================
# ============ Component Extension Configuration ==========
# ----- ZooKeeper Configuration -----
# Address or hostname for the ZooKeeper service.
# Default: ZOOKEEPER_ADDRESS=172.28.0.1
ZOOKEEPER_ADDRESS=172.28.0.5
# Port for ZooKeeper service.
# Default: ZOOKEEPER_PORT=12181
ZOOKEEPER_PORT=12181
# ----- MongoDB Configuration -----
# Address or hostname for the MongoDB service.
# Default: MONGO_ADDRESS=172.28.0.1
MONGO_ADDRESS=172.28.0.2
# Port on which MongoDB service is running.
# Default: MONGO_PORT=37017
# MONGO_PORT=37017
# Username to authenticate with the MongoDB service.
# Default: MONGO_USERNAME=root
# MONGO_USERNAME=root
# Password to authenticate with the MongoDB service.
# Default: MONGO_PASSWORD=openIM123
MONGO_PASSWORD=openIM123
# Name of the database in MongoDB to be used.
# Default: MONGO_DATABASE=openIM_v3
MONGO_DATABASE=openIM_v3
# ----- Redis Configuration -----
# Address or hostname for the Redis service.
# Default: REDIS_ADDRESS=172.28.0.1
REDIS_ADDRESS=172.28.0.3
# Port on which Redis in-memory data structure store is running.
# Default: REDIS_PORT=16379
REDIS_PORT=16379
# Password to authenticate with the Redis service.
# Default: REDIS_PASSWORD=openIM123
REDIS_PASSWORD=openIM123
# ----- Kafka Configuration -----
# Address or hostname for the Kafka service.
# Default: KAFKA_ADDRESS=172.28.0.1
KAFKA_ADDRESS=172.28.0.4
# Kakfa username to authenticate with the Kafka service.
# KAFKA_USERNAME=''
# Port on which Kafka distributed streaming platform is running.
# Default: KAFKA_PORT=19092
KAFKA_PORT=19094
# Topic in Kafka for storing the latest messages in Redis.
# Default: KAFKA_LATESTMSG_REDIS_TOPIC=latestMsgToRedis
KAFKA_LATESTMSG_REDIS_TOPIC=latestMsgToRedis
# Topic in Kafka for pushing messages (e.g. notifications or updates).
# Default: KAFKA_MSG_PUSH_TOPIC=msgToPush
KAFKA_MSG_PUSH_TOPIC=msgToPush
# Topic in Kafka for storing offline messages in MongoDB.
# Default: KAFKA_OFFLINEMSG_MONGO_TOPIC=offlineMsgToMongoMysql
KAFKA_OFFLINEMSG_MONGO_TOPIC=offlineMsgToMongoMysql
# ----- MinIO Configuration ----
# Address or hostname for the MinIO object storage service.
# Default: MINIO_ADDRESS=172.28.0.1
MINIO_ADDRESS=172.28.0.6
# Port on which MinIO object storage service is running.
# Default: MINIO_PORT=10005
MINIO_PORT=10005
# Access key to authenticate with the MinIO service.
# Default: MINIO_ACCESS_KEY=root
# MINIO_ACCESS_KEY=root
# Secret key corresponding to the access key for MinIO authentication.
# Default: MINIO_SECRET_KEY=openIM123
MINIO_SECRET_KEY=openIM123
# ----- Prometheus Configuration -----
# Address or hostname for the Prometheus service.
# Default: PROMETHEUS_ADDRESS=172.28.0.1
PROMETHEUS_ADDRESS=172.28.0.10
# Port on which Prometheus service is running.
# Default: PROMETHEUS_PORT=19090
PROMETHEUS_PORT=19090
# ----- Grafana Configuration -----
# Address or hostname for the Grafana service.
# Default: GRAFANA_ADDRESS=172.28.0.1
GRAFANA_ADDRESS=172.28.0.11
# Port on which Grafana service is running.
# Default: GRAFANA_PORT=13000
GRAFANA_PORT=13000
# ======================================
# ============ OpenIM Web ===============
# ======================================
# Path to the OpenIM web distribution.
# Default: OPENIM_WEB_DIST_PATH=/app/dist
OPENIM_WEB_DIST_PATH=/app/dist
# Port on which OpenIM web service is running.
# Default: OPENIM_WEB_PORT=11001
OPENIM_WEB_PORT=11001
# Address or hostname for the OpenIM web service.
# Default: OPENIM_WEB_ADDRESS=172.28.0.1
OPENIM_WEB_ADDRESS=172.28.0.7
# ======================================
# ========= OpenIM Server ==============
# ======================================
# Address or hostname for the OpenIM server.
# Default: OPENIM_SERVER_ADDRESS=172.28.0.1
OPENIM_SERVER_ADDRESS=172.28.0.8
# Port for the OpenIM WebSockets.
# Default: OPENIM_WS_PORT=10001
OPENIM_WS_PORT=10001
# Port for the OpenIM API.
# Default: API_OPENIM_PORT=10002
API_OPENIM_PORT=10002
# ======================================
# ========== OpenIM Chat ===============
# ======================================
# Branch name for OpenIM chat.
# Default: CHAT_IMAGE_VERSION=main
# https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/version.md
CHAT_IMAGE_VERSION=main
# Address or hostname for the OpenIM chat service.
# Default: OPENIM_CHAT_ADDRESS=172.28.0.1
OPENIM_CHAT_ADDRESS=172.28.0.9
# Port for the OpenIM chat API.
# Default: OPENIM_CHAT_API_PORT=10008
OPENIM_CHAT_API_PORT=10008
# Directory path for storing data files or related information for OpenIM chat.
# Default: OPENIM_CHAT_DATA_DIR=./openim-chat/main
OPENIM_CHAT_DATA_DIR=./openim-chat/main
# ======================================
# ========== OpenIM Admin ==============
# ======================================
# Branch name for OpenIM server.
# Default: SERVER_IMAGE_VERSION=main
SERVER_IMAGE_VERSION=main
# Port for the OpenIM admin API.
# Default: OPENIM_ADMIN_API_PORT=10009
OPENIM_ADMIN_API_PORT=10009
# Port for the node exporter.
# Default: NODE_EXPORTER_PORT=19100
NODE_EXPORTER_PORT=19100
# Port for the prometheus.
# Default: PROMETHEUS_PORT=19090
PROMETHEUS_PORT=19090
# Port for the grafana.
# Default: GRAFANA_PORT=13000
GRAFANA_PORT=13000
# Port for the admin front.
# Default: OPENIM_ADMIN_FRONT_PORT=11002
OPENIM_ADMIN_FRONT_PORT=11002
# Port for the alertmanager.
# Default: ALERT_MANAGER_PORT=19093
ALERT_MANAGER_PORT=19093
@@ -1,36 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
groups:
- name: instance_down
rules:
- alert: InstanceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Instance {{ $labels.instance }} down"
description: "{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 1 minutes."
- name: database_insert_failure_alerts
rules:
- alert: DatabaseInsertFailed
expr: (increase(msg_insert_redis_failed_total[5m]) > 0) or (increase(msg_insert_mongo_failed_total[5m]) > 0)
for: 1m
labels:
severity: critical
annotations:
summary: "Increase in MsgInsertRedisFailedCounter or MsgInsertMongoFailedCounter detected"
description: "Either MsgInsertRedisFailedCounter or MsgInsertMongoFailedCounter has increased in the last 5 minutes, indicating failures in message insert operations to Redis or MongoDB,maybe the redis or mongodb is crash."
-354
View File
@@ -1,354 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Determines if a message should be sent. If set to false, it triggers a silent sync without a message. If true, it requires triggering a conversation.
# For rpc notification, send twice: once as a message and once as a notification.
# The options field 'isNotification' indicates if it's a notification.
groupCreated:
isSendMsg: true
# Reliability level of the message sending.
# Set to 1 to send only when online, 2 for guaranteed delivery.
reliabilityLevel: 1
# This setting is effective only when 'isSendMsg' is true.
# It controls whether to count unread messages.
unreadCount: false
# Configuration for offline push notifications.
offlinePush:
# Enables or disables offline push notifications.
enable: false
# Title for the notification when a group is created.
title: "create group title"
# Description for the notification.
desc: "create group desc"
# Additional information for the notification.
ext: "create group ext"
# Content type is not added here.
# Content should use a JSON structure conforming to the protobuf format.
groupInfoSet:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupInfoSet title"
desc: "groupInfoSet desc"
ext: "groupInfoSet ext"
joinGroupApplication:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "joinGroupApplication title"
desc: "joinGroupApplication desc"
ext: "joinGroupApplication ext"
memberQuit:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "memberQuit title"
desc: "memberQuit desc"
ext: "memberQuit ext"
groupApplicationAccepted:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupApplicationAccepted title"
desc: "groupApplicationAccepted desc"
ext: "groupApplicationAccepted ext"
groupApplicationRejected:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: " title"
desc: " desc"
ext: " ext"
groupOwnerTransferred:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupOwnerTransferred title"
desc: "groupOwnerTransferred desc"
ext: "groupOwnerTransferred ext"
memberKicked:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "memberKicked title"
desc: "memberKicked desc"
ext: "memberKicked ext"
memberInvited:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "memberInvited title"
desc: "memberInvited desc"
ext: "memberInvited ext"
memberEnter:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "memberEnter title"
desc: "memberEnter desc"
ext: "memberEnter ext"
groupDismissed:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupDismissed title"
desc: "groupDismissed desc"
ext: "groupDismissed ext"
groupMuted:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupMuted title"
desc: "groupMuted desc"
ext: "groupMuted ext"
groupCancelMuted:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupCancelMuted title"
desc: "groupCancelMuted desc"
ext: "groupCancelMuted ext"
defaultTips:
tips: "group Cancel Muted"
groupMemberMuted:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupMemberMuted title"
desc: "groupMemberMuted desc"
ext: "groupMemberMuted ext"
groupMemberCancelMuted:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupMemberCancelMuted title"
desc: "groupMemberCancelMuted desc"
ext: "groupMemberCancelMuted ext"
groupMemberInfoSet:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupMemberInfoSet title"
desc: "groupMemberInfoSet desc"
ext: "groupMemberInfoSet ext"
groupInfoSetAnnouncement:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupInfoSetAnnouncement title"
desc: "groupInfoSetAnnouncement desc"
ext: "groupInfoSetAnnouncement ext"
groupInfoSetName:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "groupInfoSetName title"
desc: "groupInfoSetName desc"
ext: "groupInfoSetName ext"
#############################friend#################################
friendApplicationAdded:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "Somebody applies to add you as a friend"
desc: "Somebody applies to add you as a friend"
ext: "Somebody applies to add you as a friend"
friendApplicationApproved:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "Someone applies to add your friend application"
desc: "Someone applies to add your friend application"
ext: "Someone applies to add your friend application"
friendApplicationRejected:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "Someone rejected your friend application"
desc: "Someone rejected your friend application"
ext: "Someone rejected your friend application"
friendAdded:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "We have become friends"
desc: "We have become friends"
ext: "We have become friends"
friendDeleted:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "deleted a friend"
desc: "deleted a friend"
ext: "deleted a friend"
friendRemarkSet:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "Your friend's profile has been changed"
desc: "Your friend's profile has been changed"
ext: "Your friend's profile has been changed"
blackAdded:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "blocked a user"
desc: "blocked a user"
ext: "blocked a user"
blackDeleted:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "Remove a blocked user"
desc: "Remove a blocked user"
ext: "Remove a blocked user"
friendInfoUpdated:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "friend info updated"
desc: "friend info updated"
ext: "friend info updated"
#####################user#########################
userInfoUpdated:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "Remove a blocked user"
desc: "Remove a blocked user"
ext: "Remove a blocked user"
userStatusChanged:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: false
title: "user status changed"
desc: "user status changed"
ext: "user status changed"
#####################conversation#########################
conversationChanged:
isSendMsg: false
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "conversation changed"
desc: "conversation changed"
ext: "conversation changed"
conversationSetPrivate:
isSendMsg: true
reliabilityLevel: 1
unreadCount: false
offlinePush:
enable: true
title: "burn after reading"
desc: "burn after reading"
ext: "burn after reading"
-172
View File
@@ -1,172 +0,0 @@
upstream im_msg_gateway{
server 127.0.0.1:10001; #IM Message server address Multiple can be specified according to the deployment
}
upstream im_api{
server 127.0.0.1:10002; #IM Group user api server address Multiple can be specified according to the deployment
}
upstream im_grafana{
server 127.0.0.1:10007; #IM Statistical server address The machine where docker-compose starts
}
upstream im_chat_api{
server 127.0.0.1:10008; #IM Business version login registration server address Multiple can be specified according to the deployment
}
upstream im_admin_api{
server 127.0.0.1:10009; #IM The admin address of the commercial version can specify multiple units according to the deployment situation
}
upstream im_open_rtc{
server 127.0.0.1:7880; #rtc Audio and video call server address Multiple devices can be specified according to the deployment
}
upstream minio_s3_2 {
least_conn;
server 127.0.0.1:10005;
}
upstream minio_console_2 {
least_conn;
server 127.0.0.1:9090;
}
server {
listen 443;
server_name your-domain.com; #your-domain.com
ssl on;
ssl_certificate /etc/nginx/conf.d/ssl/your-domain.com.crt; #2 Certificate
ssl_certificate_key /etc/nginx/conf.d/ssl/your-domain.com.key; #3 Certificate
ssl_session_timeout 5m;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/wasm;
gzip_vary off;
gzip_disable "MSIE [1-6]\.";
error_page 405 =200 $uri;
default_type application/wasm;
location /{ #web demo
proxy_set_header Host $host;
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-NginX-Proxy true;
root /data1/online/Pc-Web-Demo/build/; # web im static resource storage path
index index.html;
try_files $uri $uri/ /index.html;
}
location /msg_gateway { #10001 ws
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_msg_gateway/;
}
location ^~/api/ { #10002 api
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_api/;
}
location ^~/grafana/ { #10007 prometheus
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_grafana/;
}
location ^~/chat/ { #10008 im_chat_api
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_chat_api/;
}
location ^~/complete_admin/ { #10009 admin
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_admin_api/;
}
location ^~/open_rtc/ { #7880 rtc
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_open_rtc/;
}
}
server {
listen 80;
server_name test-web.rentsoft.cn ; #1 web im end domain name
rewrite ^(.*)$ https://${server_name}$1 permanent;
}
server {
listen 443;
server_name your-domain.com; #your-domain.com
ssl on;
ssl_certificate /etc/nginx/conf.d/ssl/your-domain.com.crt; #Certificate
ssl_certificate_key /etc/nginx/conf.d/ssl/your-domain.com.key; #Certificate
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/wasm;
gzip_vary off;
gzip_disable "MSIE [1-6]\.";
# Allow special characters in headers
ignore_invalid_headers off;
# Allow any size file to be uploaded.
# Set to a value such as 1000m; to restrict file size to a specific value
client_max_body_size 0;
# Disable buffering
proxy_buffering off;
proxy_request_buffering off;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 300;
# Default is HTTP/1, keepalive is only enabled in HTTP/1.1
proxy_http_version 1.1;
proxy_set_header Connection "";
chunked_transfer_encoding off;
proxy_pass http://minio_s3_2; # This uses the upstream directive definition to load balance
}
location /minio/ui {
rewrite ^/minio/ui/(.*) /$1 break;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
# This is necessary to pass the correct IP to be hashed
real_ip_header X-Real-IP;
proxy_connect_timeout 300;
# To support websockets in MinIO versions released after January 2023
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
chunked_transfer_encoding off;
proxy_pass http://minio_console_2; # This uses the upstream directive definition to load balance
}
}
File diff suppressed because it is too large Load Diff
-99
View File
@@ -1,99 +0,0 @@
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets: ['172.28.0.1:19093']
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "instance-down-rules.yml"
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label "job='job_name'"" to any timeseries scraped from this config.
# Monitored information captured by prometheus
- job_name: 'node-exporter'
static_configs:
- targets: [ '172.28.0.1:19100' ]
labels:
namespace: 'default'
# prometheus fetches application services
- job_name: 'openimserver-openim-api'
static_configs:
- targets: [ '172.28.0.1:20100' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-msggateway'
static_configs:
- targets: [ '172.28.0.1:20140' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-msgtransfer'
static_configs:
- targets: [ 172.28.0.1:21400, 172.28.0.1:21401, 172.28.0.1:21402, 172.28.0.1:21403 ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-push'
static_configs:
- targets: [ '172.28.0.1:20170' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-auth'
static_configs:
- targets: [ '172.28.0.1:20160' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-conversation'
static_configs:
- targets: [ '172.28.0.1:20230' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-friend'
static_configs:
- targets: [ '172.28.0.1:20120' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-group'
static_configs:
- targets: [ '172.28.0.1:20150' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-msg'
static_configs:
- targets: [ '172.28.0.1:20130' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-third'
static_configs:
- targets: [ '172.28.0.1:21301' ]
labels:
namespace: 'default'
- job_name: 'openimserver-openim-rpc-user'
static_configs:
- targets: [ '172.28.0.1:20110' ]
labels:
namespace: 'default'
File diff suppressed because it is too large Load Diff
+27 -2
View File
@@ -27,7 +27,7 @@ services:
- wiredTigerCacheSizeGB=1 - wiredTigerCacheSizeGB=1
- MONGO_INITDB_ROOT_USERNAME=${MONGO_USERNAME:-root} - MONGO_INITDB_ROOT_USERNAME=${MONGO_USERNAME:-root}
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_PASSWORD:-openIM123} - MONGO_INITDB_ROOT_PASSWORD=${MONGO_PASSWORD:-openIM123}
- MONGO_INITDB_DATABASE=${MONGO_DATABASE:-openIM_v3} - MONGO_INITDB_DATABASE=${MONGO_DATABASE:-openim_v3}
- MONGO_OPENIM_USERNAME=${MONGO_OPENIM_USERNAME:-openIM} # Non-root username - MONGO_OPENIM_USERNAME=${MONGO_OPENIM_USERNAME:-openIM} # Non-root username
- MONGO_OPENIM_PASSWORD=${MONGO_OPENIM_PASSWORD:-openIM123456} # Non-root password - MONGO_OPENIM_PASSWORD=${MONGO_OPENIM_PASSWORD:-openIM123456} # Non-root password
restart: always restart: always
@@ -87,6 +87,7 @@ services:
- KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=0@<your_host>:9093 - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=0@<your_host>:9093
- KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094 - KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094
- KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,EXTERNAL://${DOCKER_BRIDGE_GATEWAY:-172.28.0.1}:${KAFKA_PORT:-19094} - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,EXTERNAL://${DOCKER_BRIDGE_GATEWAY:-172.28.0.1}:${KAFKA_PORT:-19094}
# - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://kafka:9092,EXTERNAL://127.0.0.1:${KAFKA_PORT:-19094} # Mac Deployment
- KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT,PLAINTEXT:PLAINTEXT - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT,PLAINTEXT:PLAINTEXT
- KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER
networks: networks:
@@ -114,6 +115,7 @@ services:
openim-web: openim-web:
image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-web:${OPENIM_WEB_IMAGE_VERSION:-v3.5.0-docker} image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-web:${OPENIM_WEB_IMAGE_VERSION:-v3.5.0-docker}
container_name: openim-web container_name: openim-web
platform: linux/amd64
restart: always restart: always
ports: ports:
- "${OPENIM_WEB_PORT:-11001}:80" - "${OPENIM_WEB_PORT:-11001}:80"
@@ -122,7 +124,7 @@ services:
ipv4_address: ${OPENIM_WEB_NETWORK_ADDRESS:-172.28.0.7} ipv4_address: ${OPENIM_WEB_NETWORK_ADDRESS:-172.28.0.7}
### TODO: Uncomment, or deploy using openim docker: https://github.com/openimsdk/openim-docker ### TODO: Uncomment, or deploy using openim docker: https://github.com/openimsdk/openim-docker
# Uncomment and configure the following services as needed ### Uncomment and configure the following services as needed
# openim-server: # openim-server:
# image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-server:${SERVER_IMAGE_VERSION:-main} # image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-server:${SERVER_IMAGE_VERSION:-main}
@@ -171,6 +173,23 @@ services:
# server: # server:
# ipv4_address: ${OPENIM_SERVER_NETWORK_ADDRESS:-172.28.0.8} # ipv4_address: ${OPENIM_SERVER_NETWORK_ADDRESS:-172.28.0.8}
### TODO: mysql is required to deploy the openim-chat component
# mysql:
# image: mysql:${MYSQL_IMAGE_VERSION:-5.7}
# platform: linux/amd64
# ports:
# - "${MYSQL_PORT:-13306}:3306"
# container_name: mysql
# volumes:
# - "${DATA_DIR:-./}/components/mysql/data:/var/lib/mysql"
# - "/etc/localtime:/etc/localtime"
# environment:
# MYSQL_ROOT_PASSWORD: "${MYSQL_PASSWORD:-openIM123}"
# restart: always
# networks:
# server:
# ipv4_address: ${MYSQL_NETWORK_ADDRESS:-172.28.0.15}
# openim-chat: # openim-chat:
# image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-chat:${CHAT_IMAGE_VERSION:-main} # image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-chat:${CHAT_IMAGE_VERSION:-main}
# container_name: openim-chat # container_name: openim-chat
@@ -198,6 +217,11 @@ services:
# - "${DATA_DIR:-./}/components/openim-chat/config:/openim/openim-chat/config" # - "${DATA_DIR:-./}/components/openim-chat/config:/openim/openim-chat/config"
# restart: always # restart: always
# # user: root:root # # user: root:root
# depends_on:
# - mysql
# - kafka
# - redis
# - zookeeper
# logging: # logging:
# driver: json-file # driver: json-file
# options: # options:
@@ -211,6 +235,7 @@ services:
# # https://github.com/openimsdk/open-im-server/issues/1662 # # https://github.com/openimsdk/open-im-server/issues/1662
# image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-admin:${ADMIN_FRONT_VERSION:-toc-base-open-docker.35} # image: ${IMAGE_REGISTRY:-ghcr.io/openimsdk}/openim-admin:${ADMIN_FRONT_VERSION:-toc-base-open-docker.35}
# container_name: openim-admin # container_name: openim-admin
# platform: linux/amd64
# restart: always # restart: always
# ports: # ports:
# - "${OPENIM_ADMIN_FRONT_PORT:-11002}:80" # - "${OPENIM_ADMIN_FRONT_PORT:-11002}:80"
+5 -3
View File
@@ -4,8 +4,8 @@ go 1.19
require ( require (
firebase.google.com/go v3.13.0+incompatible firebase.google.com/go v3.13.0+incompatible
github.com/OpenIMSDK/protocol v0.0.47 github.com/OpenIMSDK/protocol v0.0.48
github.com/OpenIMSDK/tools v0.0.29 github.com/OpenIMSDK/tools v0.0.23
github.com/bwmarrin/snowflake v0.3.0 // indirect github.com/bwmarrin/snowflake v0.3.0 // indirect
github.com/dtm-labs/rockscache v0.1.1 github.com/dtm-labs/rockscache v0.1.1
github.com/gin-gonic/gin v1.9.1 github.com/gin-gonic/gin v1.9.1
@@ -127,7 +127,7 @@ require (
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
go.opencensus.io v0.24.0 // indirect go.opencensus.io v0.24.0 // indirect
go.uber.org/atomic v1.7.0 // indirect go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.6.0 // indirect
golang.org/x/arch v0.3.0 // indirect golang.org/x/arch v0.3.0 // indirect
golang.org/x/net v0.17.0 // indirect golang.org/x/net v0.17.0 // indirect
golang.org/x/oauth2 v0.13.0 // indirect golang.org/x/oauth2 v0.13.0 // indirect
@@ -156,3 +156,5 @@ require (
golang.org/x/crypto v0.17.0 // indirect golang.org/x/crypto v0.17.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect
) )
replace github.com/OpenIMSDK/protocol v0.0.47 => github.com/AndrewZuo01/protocol v0.0.0-20240112093520-fd9c53e27b94
+6 -6
View File
@@ -15,13 +15,13 @@ cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/o
cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E=
firebase.google.com/go v3.13.0+incompatible h1:3TdYC3DDi6aHn20qoRkxwGqNgdjtblwVAyRLQwGn/+4= firebase.google.com/go v3.13.0+incompatible h1:3TdYC3DDi6aHn20qoRkxwGqNgdjtblwVAyRLQwGn/+4=
firebase.google.com/go v3.13.0+incompatible/go.mod h1:xlah6XbEyW6tbfSklcfe5FHJIwjt8toICdV5Wh9ptHs= firebase.google.com/go v3.13.0+incompatible/go.mod h1:xlah6XbEyW6tbfSklcfe5FHJIwjt8toICdV5Wh9ptHs=
github.com/AndrewZuo01/protocol v0.0.0-20240112093520-fd9c53e27b94 h1:o86vkek41ZrQqoBGqyKvS0z6N0uJj64mpzK72OkDZVM=
github.com/AndrewZuo01/protocol v0.0.0-20240112093520-fd9c53e27b94/go.mod h1:F25dFrwrIx3lkNoiuf6FkCfxuwf8L4Z8UIsdTHP/r0Y=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/IBM/sarama v1.41.3 h1:MWBEJ12vHC8coMjdEXFq/6ftO6DUZnQlFYcxtOJFa7c= github.com/IBM/sarama v1.41.3 h1:MWBEJ12vHC8coMjdEXFq/6ftO6DUZnQlFYcxtOJFa7c=
github.com/IBM/sarama v1.41.3/go.mod h1:Xxho9HkHd4K/MDUo/T/sOqwtX/17D33++E9Wib6hUdQ= github.com/IBM/sarama v1.41.3/go.mod h1:Xxho9HkHd4K/MDUo/T/sOqwtX/17D33++E9Wib6hUdQ=
github.com/OpenIMSDK/protocol v0.0.48 h1:8MIMjyzJRsruYhVv2ZKArFiOveroaofDOb3dlAdgjsw= github.com/OpenIMSDK/tools v0.0.23 h1:xozfrGzhbpNPlDTap5DLVPk+JfgZ/ZyIj4Cuu3/bm9w=
github.com/OpenIMSDK/protocol v0.0.48/go.mod h1:F25dFrwrIx3lkNoiuf6FkCfxuwf8L4Z8UIsdTHP/r0Y= github.com/OpenIMSDK/tools v0.0.23/go.mod h1:eg+q4A34Qmu73xkY0mt37FHGMCMfC6CtmOnm0kFEGFI=
github.com/OpenIMSDK/tools v0.0.29 h1:NS4PEwYl9sX3SWsMjDOLVxMo3LcTWREMr+2cjzWjcqc=
github.com/OpenIMSDK/tools v0.0.29/go.mod h1:eg+q4A34Qmu73xkY0mt37FHGMCMfC6CtmOnm0kFEGFI=
github.com/QcloudApi/qcloud_sign_golang v0.0.0-20141224014652-e4130a326409/go.mod h1:1pk82RBxDY/JZnPQrtqHlUFfCctgdorsd9M06fMynOM= github.com/QcloudApi/qcloud_sign_golang v0.0.0-20141224014652-e4130a326409/go.mod h1:1pk82RBxDY/JZnPQrtqHlUFfCctgdorsd9M06fMynOM=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs= github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs=
@@ -356,8 +356,8 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/automaxprocs v1.5.3 h1:kWazyxZUrS3Gs4qUpbwo5kEIMGe/DAvi5Z4tl2NW4j8= go.uber.org/automaxprocs v1.5.3 h1:kWazyxZUrS3Gs4qUpbwo5kEIMGe/DAvi5Z4tl2NW4j8=
go.uber.org/automaxprocs v1.5.3/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0= go.uber.org/automaxprocs v1.5.3/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
+6 -5
View File
@@ -4,14 +4,15 @@ use (
. .
./test/typecheck ./test/typecheck
./tools/changelog ./tools/changelog
//./tools/imctl ./tools/component
./tools/data-conversion
./tools/formitychecker
./tools/imctl
./tools/infra ./tools/infra
./tools/ncpu ./tools/ncpu
./tools/openim-web ./tools/openim-web
./tools/up35
./tools/url2im
./tools/versionchecker ./tools/versionchecker
./tools/yamlfmt ./tools/yamlfmt
./tools/component
./tools/url2im
./tools/data-conversion
./tools/up35
) )
+1
View File
@@ -83,6 +83,7 @@ func NewGinRouter(discov discoveryregistry.SvcDiscoveryRegistry, rdb redis.Unive
userRouterGroup.POST("/process_user_command_delete", ParseToken, u.ProcessUserCommandDelete) userRouterGroup.POST("/process_user_command_delete", ParseToken, u.ProcessUserCommandDelete)
userRouterGroup.POST("/process_user_command_update", ParseToken, u.ProcessUserCommandUpdate) userRouterGroup.POST("/process_user_command_update", ParseToken, u.ProcessUserCommandUpdate)
userRouterGroup.POST("/process_user_command_get", ParseToken, u.ProcessUserCommandGet) userRouterGroup.POST("/process_user_command_get", ParseToken, u.ProcessUserCommandGet)
userRouterGroup.POST("/process_user_command_get_all", ParseToken, u.ProcessUserCommandGetAll)
userRouterGroup.POST("/add_notification_account", ParseToken, u.AddNotificationAccount) userRouterGroup.POST("/add_notification_account", ParseToken, u.AddNotificationAccount)
userRouterGroup.POST("/update_notification_account", ParseToken, u.UpdateNotificationAccountInfo) userRouterGroup.POST("/update_notification_account", ParseToken, u.UpdateNotificationAccountInfo)
+5
View File
@@ -221,6 +221,11 @@ func (u *UserApi) ProcessUserCommandGet(c *gin.Context) {
a2r.Call(user.UserClient.ProcessUserCommandGet, u.Client, c) a2r.Call(user.UserClient.ProcessUserCommandGet, u.Client, c)
} }
// ProcessUserCommandGet user general function get all
func (u *UserApi) ProcessUserCommandGetAll(c *gin.Context) {
a2r.Call(user.UserClient.ProcessUserCommandGetAll, u.Client, c)
}
func (u *UserApi) AddNotificationAccount(c *gin.Context) { func (u *UserApi) AddNotificationAccount(c *gin.Context) {
a2r.Call(user.UserClient.AddNotificationAccount, u.Client, c) a2r.Call(user.UserClient.AddNotificationAccount, u.Client, c)
} }
+3 -3
View File
@@ -37,7 +37,7 @@ func callbackOfflinePush(
msg *sdkws.MsgData, msg *sdkws.MsgData,
offlinePushUserIDs *[]string, offlinePushUserIDs *[]string,
) error { ) error {
if !config.Config.Callback.CallbackOfflinePush.Enable { if !config.Config.Callback.CallbackOfflinePush.Enable || msg.ContentType == constant.Typing {
return nil return nil
} }
req := &callbackstruct.CallbackBeforePushReq{ req := &callbackstruct.CallbackBeforePushReq{
@@ -73,7 +73,7 @@ func callbackOfflinePush(
} }
func callbackOnlinePush(ctx context.Context, userIDs []string, msg *sdkws.MsgData) error { func callbackOnlinePush(ctx context.Context, userIDs []string, msg *sdkws.MsgData) error {
if !config.Config.Callback.CallbackOnlinePush.Enable || utils.Contain(msg.SendID, userIDs...) { if !config.Config.Callback.CallbackOnlinePush.Enable || utils.Contain(msg.SendID, userIDs...) || msg.ContentType == constant.Typing {
return nil return nil
} }
req := callbackstruct.CallbackBeforePushReq{ req := callbackstruct.CallbackBeforePushReq{
@@ -107,7 +107,7 @@ func callbackBeforeSuperGroupOnlinePush(
msg *sdkws.MsgData, msg *sdkws.MsgData,
pushToUserIDs *[]string, pushToUserIDs *[]string,
) error { ) error {
if !config.Config.Callback.CallbackBeforeSuperGroupOnlinePush.Enable { if !config.Config.Callback.CallbackBeforeSuperGroupOnlinePush.Enable || msg.ContentType == constant.Typing {
return nil return nil
} }
req := callbackstruct.CallbackBeforeSuperGroupOnlinePushReq{ req := callbackstruct.CallbackBeforeSuperGroupOnlinePushReq{
+2 -3
View File
@@ -101,11 +101,9 @@ func (p *Pusher) DeleteMemberAndSetConversationSeq(ctx context.Context, groupID
func (p *Pusher) Push2User(ctx context.Context, userIDs []string, msg *sdkws.MsgData) error { func (p *Pusher) Push2User(ctx context.Context, userIDs []string, msg *sdkws.MsgData) error {
log.ZDebug(ctx, "Get msg from msg_transfer And push msg", "userIDs", userIDs, "msg", msg.String()) log.ZDebug(ctx, "Get msg from msg_transfer And push msg", "userIDs", userIDs, "msg", msg.String())
// callback
if err := callbackOnlinePush(ctx, userIDs, msg); err != nil { if err := callbackOnlinePush(ctx, userIDs, msg); err != nil {
return err return err
} }
// push // push
wsResults, err := p.GetConnsAndOnlinePush(ctx, msg, userIDs) wsResults, err := p.GetConnsAndOnlinePush(ctx, msg, userIDs)
if err != nil { if err != nil {
@@ -120,7 +118,7 @@ func (p *Pusher) Push2User(ctx context.Context, userIDs []string, msg *sdkws.Msg
} }
for _, v := range wsResults { for _, v := range wsResults {
if msg.SendID != v.UserID && (!v.OnlinePush) { if !v.OnlinePush && msg.SendID == v.UserID {
if err = callbackOfflinePush(ctx, userIDs, msg, &[]string{}); err != nil { if err = callbackOfflinePush(ctx, userIDs, msg, &[]string{}); err != nil {
return err return err
} }
@@ -130,6 +128,7 @@ func (p *Pusher) Push2User(ctx context.Context, userIDs []string, msg *sdkws.Msg
return err return err
} }
} }
} }
return nil return nil
} }
+4 -4
View File
@@ -279,20 +279,20 @@ func CallbackApplyJoinGroupBefore(ctx context.Context, req *callbackstruct.Callb
return nil return nil
} }
func CallbackTransferGroupOwnerAfter(ctx context.Context, req *pbgroup.TransferGroupOwnerReq) (err error) { func CallbackAfterTransferGroupOwner(ctx context.Context, req *pbgroup.TransferGroupOwnerReq) (err error) {
if !config.Config.Callback.CallbackTransferGroupOwnerAfter.Enable { if !config.Config.Callback.CallbackAfterTransferGroupOwner.Enable {
return nil return nil
} }
cbReq := &callbackstruct.CallbackTransferGroupOwnerReq{ cbReq := &callbackstruct.CallbackTransferGroupOwnerReq{
CallbackCommand: callbackstruct.CallbackTransferGroupOwnerAfter, CallbackCommand: callbackstruct.CallbackAfterTransferGroupOwner,
GroupID: req.GroupID, GroupID: req.GroupID,
OldOwnerUserID: req.OldOwnerUserID, OldOwnerUserID: req.OldOwnerUserID,
NewOwnerUserID: req.NewOwnerUserID, NewOwnerUserID: req.NewOwnerUserID,
} }
resp := &callbackstruct.CallbackTransferGroupOwnerResp{} resp := &callbackstruct.CallbackTransferGroupOwnerResp{}
if err = http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, cbReq, resp, config.Config.Callback.CallbackBeforeJoinGroup); err != nil { if err = http.CallBackPostReturn(ctx, config.Config.Callback.CallbackUrl, cbReq, resp, config.Config.Callback.CallbackAfterTransferGroupOwner); err != nil {
return err return err
} }
return nil return nil
+1 -1
View File
@@ -1058,7 +1058,7 @@ func (s *groupServer) TransferGroupOwner(ctx context.Context, req *pbgroup.Trans
return nil, err return nil, err
} }
if err := CallbackTransferGroupOwnerAfter(ctx, req); err != nil { if err := CallbackAfterTransferGroupOwner(ctx, req); err != nil {
return nil, err return nil, err
} }
s.Notification.GroupOwnerTransferredNotification(ctx, req) s.Notification.GroupOwnerTransferredNotification(ctx, req)
+3 -2
View File
@@ -126,14 +126,15 @@ func (m *msgServer) MarkMsgsAsRead(
} }
req_callback := &cbapi.CallbackSingleMsgReadReq{ req_callback := &cbapi.CallbackSingleMsgReadReq{
ConversationID: conversation.ConversationID,
UserID: req.UserID, UserID: req.UserID,
ConversationID: req.ConversationID,
ContentType: conversation.ConversationType,
Seqs: req.Seqs, Seqs: req.Seqs,
ContentType: conversation.ConversationType,
} }
if err = CallbackSingleMsgRead(ctx, req_callback); err != nil { if err = CallbackSingleMsgRead(ctx, req_callback); err != nil {
return nil, err return nil, err
} }
if err = m.sendMarkAsReadNotification(ctx, req.ConversationID, conversation.ConversationType, req.UserID, if err = m.sendMarkAsReadNotification(ctx, req.ConversationID, conversation.ConversationType, req.UserID,
m.conversationAndGetRecvID(conversation, req.UserID), req.Seqs, hasReadSeq); err != nil { m.conversationAndGetRecvID(conversation, req.UserID), req.Seqs, hasReadSeq); err != nil {
return return
+2
View File
@@ -65,6 +65,7 @@ func (m *msgServer) sendMsgSuperGroupChat(
if err = callbackBeforeSendGroupMsg(ctx, req); err != nil { if err = callbackBeforeSendGroupMsg(ctx, req); err != nil {
return nil, err return nil, err
} }
if err := callbackMsgModify(ctx, req); err != nil { if err := callbackMsgModify(ctx, req); err != nil {
return nil, err return nil, err
} }
@@ -167,6 +168,7 @@ func (m *msgServer) sendMsgSingleChat(ctx context.Context, req *pbmsg.SendMsgReq
if err = callbackBeforeSendSingleMsg(ctx, req); err != nil { if err = callbackBeforeSendSingleMsg(ctx, req); err != nil {
return nil, err return nil, err
} }
if err := callbackMsgModify(ctx, req); err != nil { if err := callbackMsgModify(ctx, req); err != nil {
return nil, err return nil, err
} }
+140 -14
View File
@@ -59,11 +59,6 @@ type userServer struct {
RegisterCenter registry.SvcDiscoveryRegistry RegisterCenter registry.SvcDiscoveryRegistry
} }
func (s *userServer) ProcessUserCommandGetAll(ctx context.Context, req *pbuser.ProcessUserCommandGetAllReq) (*pbuser.ProcessUserCommandGetAllResp, error) {
//TODO implement me
panic("implement me")
}
func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error { func Start(client registry.SvcDiscoveryRegistry, server *grpc.Server) error {
rdb, err := cache.NewRedis() rdb, err := cache.NewRedis()
if err != nil { if err != nil {
@@ -234,11 +229,20 @@ func (s *userServer) AccountCheck(ctx context.Context, req *pbuser.AccountCheckR
} }
func (s *userServer) GetPaginationUsers(ctx context.Context, req *pbuser.GetPaginationUsersReq) (resp *pbuser.GetPaginationUsersResp, err error) { func (s *userServer) GetPaginationUsers(ctx context.Context, req *pbuser.GetPaginationUsersReq) (resp *pbuser.GetPaginationUsersResp, err error) {
total, users, err := s.PageFindUser(ctx, constant.IMOrdinaryUser, constant.AppOrdinaryUsers, req.Pagination) if req.UserID == "" && req.NickName == "" {
if err != nil { total, users, err := s.PageFindUser(ctx, constant.IMOrdinaryUser, constant.AppOrdinaryUsers, req.Pagination)
return nil, err if err != nil {
return nil, err
}
return &pbuser.GetPaginationUsersResp{Total: int32(total), Users: convert.UsersDB2Pb(users)}, err
} else {
total, users, err := s.PageFindUserWithKeyword(ctx, constant.IMOrdinaryUser, constant.AppOrdinaryUsers, req.UserID, req.NickName, req.Pagination)
if err != nil {
return nil, err
}
return &pbuser.GetPaginationUsersResp{Total: int32(total), Users: convert.UsersDB2Pb(users)}, err
} }
return &pbuser.GetPaginationUsersResp{Total: int32(total), Users: convert.UsersDB2Pb(users)}, err
} }
func (s *userServer) UserRegister(ctx context.Context, req *pbuser.UserRegisterReq) (resp *pbuser.UserRegisterResp, err error) { func (s *userServer) UserRegister(ctx context.Context, req *pbuser.UserRegisterReq) (resp *pbuser.UserRegisterResp, err error) {
@@ -385,14 +389,51 @@ func (s *userServer) GetSubscribeUsersStatus(ctx context.Context,
// ProcessUserCommandAdd user general function add // ProcessUserCommandAdd user general function add
func (s *userServer) ProcessUserCommandAdd(ctx context.Context, req *pbuser.ProcessUserCommandAddReq) (*pbuser.ProcessUserCommandAddResp, error) { func (s *userServer) ProcessUserCommandAdd(ctx context.Context, req *pbuser.ProcessUserCommandAddReq) (*pbuser.ProcessUserCommandAddResp, error) {
err := authverify.CheckAccessV3(ctx, req.UserID)
if err != nil {
return nil, err
}
var value string
if req.Value != nil {
value = req.Value.Value
}
var ex string
if req.Ex != nil {
value = req.Ex.Value
}
// Assuming you have a method in s.UserDatabase to add a user command
err = s.UserDatabase.AddUserCommand(ctx, req.UserID, req.Type, req.Uuid, value, ex)
if err != nil {
return nil, err
}
tips := &sdkws.UserCommandAddTips{
FromUserID: req.UserID,
ToUserID: req.UserID,
}
err = s.userNotificationSender.UserCommandAddNotification(ctx, tips)
if err != nil {
return nil, err
}
return &pbuser.ProcessUserCommandAddResp{}, nil return &pbuser.ProcessUserCommandAddResp{}, nil
} }
// ProcessUserCommandDelete user general function delete // ProcessUserCommandDelete user general function delete
func (s *userServer) ProcessUserCommandDelete(ctx context.Context, req *pbuser.ProcessUserCommandDeleteReq) (*pbuser.ProcessUserCommandDeleteResp, error) { func (s *userServer) ProcessUserCommandDelete(ctx context.Context, req *pbuser.ProcessUserCommandDeleteReq) (*pbuser.ProcessUserCommandDeleteResp, error) {
// Assuming you have a method in s.UserDatabase to delete a user command err := authverify.CheckAccessV3(ctx, req.UserID)
err := s.UserDatabase.DeleteUserCommand(ctx, req.UserID, req.Type, req.Uuid) if err != nil {
return nil, err
}
err = s.UserDatabase.DeleteUserCommand(ctx, req.UserID, req.Type, req.Uuid)
if err != nil {
return nil, err
}
tips := &sdkws.UserCommandDeleteTips{
FromUserID: req.UserID,
ToUserID: req.UserID,
}
err = s.userNotificationSender.UserCommandDeleteNotification(ctx, tips)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -401,14 +442,92 @@ func (s *userServer) ProcessUserCommandDelete(ctx context.Context, req *pbuser.P
// ProcessUserCommandUpdate user general function update // ProcessUserCommandUpdate user general function update
func (s *userServer) ProcessUserCommandUpdate(ctx context.Context, req *pbuser.ProcessUserCommandUpdateReq) (*pbuser.ProcessUserCommandUpdateResp, error) { func (s *userServer) ProcessUserCommandUpdate(ctx context.Context, req *pbuser.ProcessUserCommandUpdateReq) (*pbuser.ProcessUserCommandUpdateResp, error) {
err := authverify.CheckAccessV3(ctx, req.UserID)
if err != nil {
return nil, err
}
val := make(map[string]any)
// Map fields from eax to val
if req.Value != nil {
val["value"] = req.Value.Value
}
if req.Ex != nil {
val["ex"] = req.Ex.Value
}
// Assuming you have a method in s.UserDatabase to update a user command
err = s.UserDatabase.UpdateUserCommand(ctx, req.UserID, req.Type, req.Uuid, val)
if err != nil {
return nil, err
}
tips := &sdkws.UserCommandUpdateTips{
FromUserID: req.UserID,
ToUserID: req.UserID,
}
err = s.userNotificationSender.UserCommandUpdateNotification(ctx, tips)
if err != nil {
return nil, err
}
return &pbuser.ProcessUserCommandUpdateResp{}, nil return &pbuser.ProcessUserCommandUpdateResp{}, nil
} }
func (s *userServer) ProcessUserCommandGet(ctx context.Context, req *pbuser.ProcessUserCommandGetReq) (*pbuser.ProcessUserCommandGetResp, error) { func (s *userServer) ProcessUserCommandGet(ctx context.Context, req *pbuser.ProcessUserCommandGetReq) (*pbuser.ProcessUserCommandGetResp, error) {
err := authverify.CheckAccessV3(ctx, req.UserID)
if err != nil {
return nil, err
}
// Fetch user commands from the database
commands, err := s.UserDatabase.GetUserCommands(ctx, req.UserID, req.Type)
if err != nil {
return nil, err
}
// Initialize commandInfoSlice as an empty slice
commandInfoSlice := make([]*pbuser.CommandInfoResp, 0, len(commands))
for _, command := range commands {
// No need to use index since command is already a pointer
commandInfoSlice = append(commandInfoSlice, &pbuser.CommandInfoResp{
Type: command.Type,
Uuid: command.Uuid,
Value: command.Value,
CreateTime: command.CreateTime,
Ex: command.Ex,
})
}
// Return the response with the slice // Return the response with the slice
return &pbuser.ProcessUserCommandGetResp{}, nil return &pbuser.ProcessUserCommandGetResp{CommandResp: commandInfoSlice}, nil
}
func (s *userServer) ProcessUserCommandGetAll(ctx context.Context, req *pbuser.ProcessUserCommandGetAllReq) (*pbuser.ProcessUserCommandGetAllResp, error) {
err := authverify.CheckAccessV3(ctx, req.UserID)
if err != nil {
return nil, err
}
// Fetch user commands from the database
commands, err := s.UserDatabase.GetAllUserCommands(ctx, req.UserID)
if err != nil {
return nil, err
}
// Initialize commandInfoSlice as an empty slice
commandInfoSlice := make([]*pbuser.AllCommandInfoResp, 0, len(commands))
for _, command := range commands {
// No need to use index since command is already a pointer
commandInfoSlice = append(commandInfoSlice, &pbuser.AllCommandInfoResp{
Type: command.Type,
Uuid: command.Uuid,
Value: command.Value,
CreateTime: command.CreateTime,
Ex: command.Ex,
})
}
// Return the response with the slice
return &pbuser.ProcessUserCommandGetAllResp{CommandResp: commandInfoSlice}, nil
} }
func (s *userServer) AddNotificationAccount(ctx context.Context, req *pbuser.AddNotificationAccountReq) (*pbuser.AddNotificationAccountResp, error) { func (s *userServer) AddNotificationAccount(ctx context.Context, req *pbuser.AddNotificationAccountReq) (*pbuser.AddNotificationAccountResp, error) {
@@ -481,31 +600,38 @@ func (s *userServer) UpdateNotificationAccountInfo(ctx context.Context, req *pbu
} }
func (s *userServer) SearchNotificationAccount(ctx context.Context, req *pbuser.SearchNotificationAccountReq) (*pbuser.SearchNotificationAccountResp, error) { func (s *userServer) SearchNotificationAccount(ctx context.Context, req *pbuser.SearchNotificationAccountReq) (*pbuser.SearchNotificationAccountResp, error) {
// Check if user is an admin
if err := authverify.CheckIMAdmin(ctx); err != nil { if err := authverify.CheckIMAdmin(ctx); err != nil {
return nil, err return nil, err
} }
var users []*relation.UserModel var users []*relation.UserModel
var err error var err error
// If a keyword is provided in the request
if req.Keyword != "" { if req.Keyword != "" {
// Find users by keyword
users, err = s.UserDatabase.Find(ctx, []string{req.Keyword}) users, err = s.UserDatabase.Find(ctx, []string{req.Keyword})
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Convert users to response format
resp := s.userModelToResp(users, req.Pagination) resp := s.userModelToResp(users, req.Pagination)
if resp.Total != 0 { if resp.Total != 0 {
return resp, nil return resp, nil
} }
// Find users by nickname if no users found by keyword
users, err = s.UserDatabase.FindByNickname(ctx, req.Keyword) users, err = s.UserDatabase.FindByNickname(ctx, req.Keyword)
if err != nil { if err != nil {
return nil, err return nil, err
} }
resp = s.userModelToResp(users, req.Pagination) resp = s.userModelToResp(users, req.Pagination)
return resp, nil return resp, nil
return resp, nil
} }
// If no keyword, find users with notification settings
users, err = s.UserDatabase.FindNotification(ctx, constant.AppNotificationAdmin) users, err = s.UserDatabase.FindNotification(ctx, constant.AppNotificationAdmin)
if err != nil { if err != nil {
return nil, err return nil, err
+1 -1
View File
@@ -41,7 +41,7 @@ const (
CallbackBeforeUpdateUserInfoExCommand = "callbackBeforeUpdateUserInfoExCommand" CallbackBeforeUpdateUserInfoExCommand = "callbackBeforeUpdateUserInfoExCommand"
CallbackBeforeUserRegisterCommand = "callbackBeforeUserRegisterCommand" CallbackBeforeUserRegisterCommand = "callbackBeforeUserRegisterCommand"
CallbackAfterUserRegisterCommand = "callbackAfterUserRegisterCommand" CallbackAfterUserRegisterCommand = "callbackAfterUserRegisterCommand"
CallbackTransferGroupOwnerAfter = "callbackTransferGroupOwnerAfter" CallbackAfterTransferGroupOwner = "callbackAfterTransferGroupOwner"
CallbackBeforeSetFriendRemark = "callbackBeforeSetFriendRemark" CallbackBeforeSetFriendRemark = "callbackBeforeSetFriendRemark"
CallbackAfterSetFriendRemark = "callbackAfterSetFriendRemark" CallbackAfterSetFriendRemark = "callbackAfterSetFriendRemark"
CallbackSingleMsgRead = "callbackSingleMsgRead" CallbackSingleMsgRead = "callbackSingleMsgRead"
+2 -2
View File
@@ -94,10 +94,10 @@ type CallbackGroupMsgReadResp struct {
type CallbackSingleMsgReadReq struct { type CallbackSingleMsgReadReq struct {
CallbackCommand `json:"callbackCommand"` CallbackCommand `json:"callbackCommand"`
UserID string `json:"userID"`
ConversationID string `json:"conversationID"` ConversationID string `json:"conversationID"`
UserID string `json:"userID"`
Seqs []int64 `json:"Seqs"`
ContentType int32 `json:"contentType"` ContentType int32 `json:"contentType"`
Seqs []int64 `json:"seqs"`
} }
type CallbackSingleMsgReadResp struct { type CallbackSingleMsgReadResp struct {
+1 -1
View File
@@ -296,7 +296,7 @@ type configStruct struct {
CallbackKillGroupMember CallBackConfig `yaml:"killGroupMember"` CallbackKillGroupMember CallBackConfig `yaml:"killGroupMember"`
CallbackDismissGroup CallBackConfig `yaml:"dismissGroup"` CallbackDismissGroup CallBackConfig `yaml:"dismissGroup"`
CallbackBeforeJoinGroup CallBackConfig `yaml:"joinGroup"` CallbackBeforeJoinGroup CallBackConfig `yaml:"joinGroup"`
CallbackTransferGroupOwnerAfter CallBackConfig `yaml:"transferGroupOwner"` CallbackAfterTransferGroupOwner CallBackConfig `yaml:"transferGroupOwner"`
CallbackBeforeInviteUserToGroup CallBackConfig `yaml:"beforeInviteUserToGroup"` CallbackBeforeInviteUserToGroup CallBackConfig `yaml:"beforeInviteUserToGroup"`
CallbackAfterJoinGroup CallBackConfig `yaml:"joinGroupAfter"` CallbackAfterJoinGroup CallBackConfig `yaml:"joinGroupAfter"`
CallbackAfterSetGroupInfo CallBackConfig `yaml:"setGroupInfoAfter"` CallbackAfterSetGroupInfo CallBackConfig `yaml:"setGroupInfoAfter"`
+17 -5
View File
@@ -24,6 +24,7 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"github.com/openimsdk/open-im-server/v3/pkg/msgprocessor" "github.com/openimsdk/open-im-server/v3/pkg/msgprocessor"
"github.com/openimsdk/open-im-server/v3/pkg/util/genutil"
) )
//go:embed version //go:embed version
@@ -37,19 +38,30 @@ const (
// return absolude path join ../config/, this is k8s container config path. // return absolude path join ../config/, this is k8s container config path.
func GetDefaultConfigPath() string { func GetDefaultConfigPath() string {
b, err := filepath.Abs(os.Args[0]) executablePath, err := os.Executable()
if err != nil { if err != nil {
fmt.Println("filepath.Abs error,err=", err) fmt.Println("GetDefaultConfigPath error:", err.Error())
return "" return ""
} }
return filepath.Join(filepath.Dir(b), "../config/")
configPath, err := genutil.OutDir(filepath.Join(filepath.Dir(executablePath), "../config/"))
if err != nil {
fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
os.Exit(1)
}
return configPath
} }
// getProjectRoot returns the absolute path of the project root directory. // getProjectRoot returns the absolute path of the project root directory.
func GetProjectRoot() string { func GetProjectRoot() string {
b, _ := filepath.Abs(os.Args[0]) executablePath, _ := os.Executable()
return filepath.Join(filepath.Dir(b), "../../../../..") projectRoot, err := genutil.OutDir(filepath.Join(filepath.Dir(executablePath), "../../../../.."))
if err != nil {
fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
os.Exit(1)
}
return projectRoot
} }
func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options { func GetOptionsByNotification(cfg NotificationConf) msgprocessor.Options {
+1 -1
View File
@@ -1 +1 @@
v3.3.0 v3.5.0
+1 -1
View File
@@ -146,7 +146,7 @@ func Test_BatchInsertChat2DB(t *testing.T) {
func GetDB() *commonMsgDatabase { func GetDB() *commonMsgDatabase {
config.Config.Mongo.Address = []string{"203.56.175.233:37017"} config.Config.Mongo.Address = []string{"203.56.175.233:37017"}
// config.Config.Mongo.Timeout = 60 // config.Config.Mongo.Timeout = 60
config.Config.Mongo.Database = "openIM_v3" config.Config.Mongo.Database = "openim_v3"
// config.Config.Mongo.Source = "admin" // config.Config.Mongo.Source = "admin"
config.Config.Mongo.Username = "root" config.Config.Mongo.Username = "root"
config.Config.Mongo.Password = "openIM123" config.Config.Mongo.Password = "openIM123"
+16 -6
View File
@@ -50,6 +50,8 @@ type UserDatabase interface {
UpdateByMap(ctx context.Context, userID string, args map[string]any) (err error) UpdateByMap(ctx context.Context, userID string, args map[string]any) (err error)
// FindUser // FindUser
PageFindUser(ctx context.Context, level1 int64, level2 int64, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error) PageFindUser(ctx context.Context, level1 int64, level2 int64, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error)
//FindUser with keyword
PageFindUserWithKeyword(ctx context.Context, level1 int64, level2 int64, userID string, nickName string, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error)
// Page If not found, no error is returned // Page If not found, no error is returned
Page(ctx context.Context, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error) Page(ctx context.Context, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error)
// IsExist true as long as one exists // IsExist true as long as one exists
@@ -78,10 +80,11 @@ type UserDatabase interface {
SetUserStatus(ctx context.Context, userID string, status, platformID int32) error SetUserStatus(ctx context.Context, userID string, status, platformID int32) error
//CRUD user command //CRUD user command
AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string, ex string) error
DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error
UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, val map[string]any) error
GetUserCommands(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error) GetUserCommands(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error)
GetAllUserCommands(ctx context.Context, userID string) ([]*user.AllCommandInfoResp, error)
} }
type userDatabase struct { type userDatabase struct {
@@ -187,6 +190,9 @@ func (u *userDatabase) Page(ctx context.Context, pagination pagination.Paginatio
func (u *userDatabase) PageFindUser(ctx context.Context, level1 int64, level2 int64, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error) { func (u *userDatabase) PageFindUser(ctx context.Context, level1 int64, level2 int64, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error) {
return u.userDB.PageFindUser(ctx, level1, level2, pagination) return u.userDB.PageFindUser(ctx, level1, level2, pagination)
} }
func (u *userDatabase) PageFindUserWithKeyword(ctx context.Context, level1 int64, level2 int64, userID, nickName string, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error) {
return u.userDB.PageFindUserWithKeyword(ctx, level1, level2, userID, nickName, pagination)
}
// IsExist Does userIDs exist? As long as there is one, it will be true. // IsExist Does userIDs exist? As long as there is one, it will be true.
func (u *userDatabase) IsExist(ctx context.Context, userIDs []string) (exist bool, err error) { func (u *userDatabase) IsExist(ctx context.Context, userIDs []string) (exist bool, err error) {
@@ -259,16 +265,20 @@ func (u *userDatabase) GetUserStatus(ctx context.Context, userIDs []string) ([]*
func (u *userDatabase) SetUserStatus(ctx context.Context, userID string, status, platformID int32) error { func (u *userDatabase) SetUserStatus(ctx context.Context, userID string, status, platformID int32) error {
return u.cache.SetUserStatus(ctx, userID, status, platformID) return u.cache.SetUserStatus(ctx, userID, status, platformID)
} }
func (u *userDatabase) AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error { func (u *userDatabase) AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string, ex string) error {
return u.userDB.AddUserCommand(ctx, userID, Type, UUID, value) return u.userDB.AddUserCommand(ctx, userID, Type, UUID, value, ex)
} }
func (u *userDatabase) DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error { func (u *userDatabase) DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error {
return u.userDB.DeleteUserCommand(ctx, userID, Type, UUID) return u.userDB.DeleteUserCommand(ctx, userID, Type, UUID)
} }
func (u *userDatabase) UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error { func (u *userDatabase) UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, val map[string]any) error {
return u.userDB.UpdateUserCommand(ctx, userID, Type, UUID, value) return u.userDB.UpdateUserCommand(ctx, userID, Type, UUID, val)
} }
func (u *userDatabase) GetUserCommands(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error) { func (u *userDatabase) GetUserCommands(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error) {
commands, err := u.userDB.GetUserCommand(ctx, userID, Type) commands, err := u.userDB.GetUserCommand(ctx, userID, Type)
return commands, err return commands, err
} }
func (u *userDatabase) GetAllUserCommands(ctx context.Context, userID string) ([]*user.AllCommandInfoResp, error) {
commands, err := u.userDB.GetAllUserCommand(ctx, userID)
return commands, err
}
+1 -2
View File
@@ -114,8 +114,7 @@ func (c *ConversationMgo) GetAllConversationIDs(ctx context.Context) ([]string,
func (c *ConversationMgo) GetAllConversationIDsNumber(ctx context.Context) (int64, error) { func (c *ConversationMgo) GetAllConversationIDsNumber(ctx context.Context) (int64, error) {
counts, err := mgoutil.Aggregate[int64](ctx, c.coll, []bson.M{ counts, err := mgoutil.Aggregate[int64](ctx, c.coll, []bson.M{
{"$group": bson.M{"_id": "$conversation_id"}}, {"$group": bson.M{"_id": "$conversation_id"}},
{"$group": bson.M{"_id": nil, "count": bson.M{"$sum": 1}}}, {"$project": bson.M{"_id": 0, "conversation_id": "$_id"}},
{"$project": bson.M{"_id": 0}},
}) })
if err != nil { if err != nil {
return 0, err return 0, err
+101 -7
View File
@@ -17,6 +17,8 @@ package mgo
import ( import (
"context" "context"
"github.com/OpenIMSDK/protocol/user" "github.com/OpenIMSDK/protocol/user"
"github.com/OpenIMSDK/tools/errs"
"go.mongodb.org/mongo-driver/bson/primitive"
"time" "time"
"github.com/OpenIMSDK/tools/mgoutil" "github.com/OpenIMSDK/tools/mgoutil"
@@ -87,6 +89,33 @@ func (u *UserMgo) PageFindUser(ctx context.Context, level1 int64, level2 int64,
return mgoutil.FindPage[*relation.UserModel](ctx, u.coll, query, pagination) return mgoutil.FindPage[*relation.UserModel](ctx, u.coll, query, pagination)
} }
func (u *UserMgo) PageFindUserWithKeyword(ctx context.Context, level1 int64, level2 int64, userID string, nickName string, pagination pagination.Pagination) (count int64, users []*relation.UserModel, err error) {
// Initialize the base query with level conditions
query := bson.M{
"$and": []bson.M{
{"app_manger_level": bson.M{"$in": []int64{level1, level2}}},
},
}
// Add userID and userName conditions to the query if they are provided
if userID != "" || nickName != "" {
userConditions := []bson.M{}
if userID != "" {
// Use regex for userID
regexPattern := primitive.Regex{Pattern: userID, Options: "i"} // 'i' for case-insensitive matching
userConditions = append(userConditions, bson.M{"user_id": regexPattern})
}
if nickName != "" {
// Use regex for userName
regexPattern := primitive.Regex{Pattern: nickName, Options: "i"} // 'i' for case-insensitive matching
userConditions = append(userConditions, bson.M{"nickname": regexPattern})
}
query["$and"] = append(query["$and"].([]bson.M), bson.M{"$or": userConditions})
}
// Perform the paginated search
return mgoutil.FindPage[*relation.UserModel](ctx, u.coll, query, pagination)
}
func (u *UserMgo) GetAllUserID(ctx context.Context, pagination pagination.Pagination) (int64, []string, error) { func (u *UserMgo) GetAllUserID(ctx context.Context, pagination pagination.Pagination) (int64, []string, error) {
return mgoutil.FindPage[string](ctx, u.coll, bson.M{}, pagination, options.Find().SetProjection(bson.M{"_id": 0, "user_id": 1})) return mgoutil.FindPage[string](ctx, u.coll, bson.M{}, pagination, options.Find().SetProjection(bson.M{"_id": 0, "user_id": 1}))
@@ -107,7 +136,7 @@ func (u *UserMgo) CountTotal(ctx context.Context, before *time.Time) (count int6
return mgoutil.Count(ctx, u.coll, bson.M{"create_time": bson.M{"$lt": before}}) return mgoutil.Count(ctx, u.coll, bson.M{"create_time": bson.M{"$lt": before}})
} }
func (u *UserMgo) AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error { func (u *UserMgo) AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string, ex string) error {
collection := u.coll.Database().Collection("userCommands") collection := u.coll.Database().Collection("userCommands")
// Create a new document instead of updating an existing one // Create a new document instead of updating an existing one
@@ -117,28 +146,48 @@ func (u *UserMgo) AddUserCommand(ctx context.Context, userID string, Type int32,
"uuid": UUID, "uuid": UUID,
"createTime": time.Now().Unix(), // assuming you want the creation time in Unix timestamp "createTime": time.Now().Unix(), // assuming you want the creation time in Unix timestamp
"value": value, "value": value,
"ex": ex,
} }
_, err := collection.InsertOne(ctx, doc) _, err := collection.InsertOne(ctx, doc)
return err return err
} }
func (u *UserMgo) DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error { func (u *UserMgo) DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error {
collection := u.coll.Database().Collection("userCommands") collection := u.coll.Database().Collection("userCommands")
filter := bson.M{"userID": userID, "type": Type, "uuid": UUID} filter := bson.M{"userID": userID, "type": Type, "uuid": UUID}
_, err := collection.DeleteOne(ctx, filter) result, err := collection.DeleteOne(ctx, filter)
if result.DeletedCount == 0 {
// No records found to update
return errs.Wrap(errs.ErrRecordNotFound)
}
return err return err
} }
func (u *UserMgo) UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error { func (u *UserMgo) UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, val map[string]any) error {
if len(val) == 0 {
return nil
}
collection := u.coll.Database().Collection("userCommands") collection := u.coll.Database().Collection("userCommands")
filter := bson.M{"userID": userID, "type": Type, "uuid": UUID} filter := bson.M{"userID": userID, "type": Type, "uuid": UUID}
update := bson.M{"$set": bson.M{"value": value}} update := bson.M{"$set": val}
_, err := collection.UpdateOne(ctx, filter, update) result, err := collection.UpdateOne(ctx, filter, update)
return err if err != nil {
return err
}
if result.MatchedCount == 0 {
// No records found to update
return errs.Wrap(errs.ErrRecordNotFound)
}
return nil
} }
func (u *UserMgo) GetUserCommand(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error) { func (u *UserMgo) GetUserCommand(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error) {
collection := u.coll.Database().Collection("userCommands") collection := u.coll.Database().Collection("userCommands")
filter := bson.M{"userID": userID, "type": Type} filter := bson.M{"userID": userID, "type": Type}
@@ -154,19 +203,23 @@ func (u *UserMgo) GetUserCommand(ctx context.Context, userID string, Type int32)
for cursor.Next(ctx) { for cursor.Next(ctx) {
var document struct { var document struct {
Type int32 `bson:"type"`
UUID string `bson:"uuid"` UUID string `bson:"uuid"`
Value string `bson:"value"` Value string `bson:"value"`
CreateTime int64 `bson:"createTime"` CreateTime int64 `bson:"createTime"`
Ex string `bson:"ex"`
} }
if err := cursor.Decode(&document); err != nil { if err := cursor.Decode(&document); err != nil {
return nil, err return nil, err
} }
commandInfo := &user.CommandInfoResp{ // Change here: use a pointer to the struct commandInfo := &user.CommandInfoResp{
Type: document.Type,
Uuid: document.UUID, Uuid: document.UUID,
Value: document.Value, Value: document.Value,
CreateTime: document.CreateTime, CreateTime: document.CreateTime,
Ex: document.Ex,
} }
commands = append(commands, commandInfo) commands = append(commands, commandInfo)
@@ -178,7 +231,48 @@ func (u *UserMgo) GetUserCommand(ctx context.Context, userID string, Type int32)
return commands, nil return commands, nil
} }
func (u *UserMgo) GetAllUserCommand(ctx context.Context, userID string) ([]*user.AllCommandInfoResp, error) {
collection := u.coll.Database().Collection("userCommands")
filter := bson.M{"userID": userID}
cursor, err := collection.Find(ctx, filter)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
// Initialize commands as a slice of pointers
commands := []*user.AllCommandInfoResp{}
for cursor.Next(ctx) {
var document struct {
Type int32 `bson:"type"`
UUID string `bson:"uuid"`
Value string `bson:"value"`
CreateTime int64 `bson:"createTime"`
Ex string `bson:"ex"`
}
if err := cursor.Decode(&document); err != nil {
return nil, err
}
commandInfo := &user.AllCommandInfoResp{
Type: document.Type,
Uuid: document.UUID,
Value: document.Value,
CreateTime: document.CreateTime,
Ex: document.Ex,
}
commands = append(commands, commandInfo)
}
if err := cursor.Err(); err != nil {
return nil, err
}
return commands, nil
}
func (u *UserMgo) CountRangeEverydayTotal(ctx context.Context, start time.Time, end time.Time) (map[string]int64, error) { func (u *UserMgo) CountRangeEverydayTotal(ctx context.Context, start time.Time, end time.Time) (map[string]int64, error) {
pipeline := bson.A{ pipeline := bson.A{
bson.M{ bson.M{
+4 -2
View File
@@ -57,6 +57,7 @@ type UserModelInterface interface {
TakeByNickname(ctx context.Context, nickname string) (user []*UserModel, err error) TakeByNickname(ctx context.Context, nickname string) (user []*UserModel, err error)
Page(ctx context.Context, pagination pagination.Pagination) (count int64, users []*UserModel, err error) Page(ctx context.Context, pagination pagination.Pagination) (count int64, users []*UserModel, err error)
PageFindUser(ctx context.Context, level1 int64, level2 int64, pagination pagination.Pagination) (count int64, users []*UserModel, err error) PageFindUser(ctx context.Context, level1 int64, level2 int64, pagination pagination.Pagination) (count int64, users []*UserModel, err error)
PageFindUserWithKeyword(ctx context.Context, level1 int64, level2 int64, userID, nickName string, pagination pagination.Pagination) (count int64, users []*UserModel, err error)
Exist(ctx context.Context, userID string) (exist bool, err error) Exist(ctx context.Context, userID string) (exist bool, err error)
GetAllUserID(ctx context.Context, pagination pagination.Pagination) (count int64, userIDs []string, err error) GetAllUserID(ctx context.Context, pagination pagination.Pagination) (count int64, userIDs []string, err error)
GetUserGlobalRecvMsgOpt(ctx context.Context, userID string) (opt int, err error) GetUserGlobalRecvMsgOpt(ctx context.Context, userID string) (opt int, err error)
@@ -65,8 +66,9 @@ type UserModelInterface interface {
// 获取范围内用户增量 // 获取范围内用户增量
CountRangeEverydayTotal(ctx context.Context, start time.Time, end time.Time) (map[string]int64, error) CountRangeEverydayTotal(ctx context.Context, start time.Time, end time.Time) (map[string]int64, error)
//CRUD user command //CRUD user command
AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error AddUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string, ex string) error
DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error DeleteUserCommand(ctx context.Context, userID string, Type int32, UUID string) error
UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, value string) error UpdateUserCommand(ctx context.Context, userID string, Type int32, UUID string, val map[string]any) error
GetUserCommand(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error) GetUserCommand(ctx context.Context, userID string, Type int32) ([]*user.CommandInfoResp, error)
GetAllUserCommand(ctx context.Context, userID string) ([]*user.AllCommandInfoResp, error)
} }
+2 -2
View File
@@ -14,14 +14,14 @@
package prommetrics package prommetrics
import ginProm "github.com/openimsdk/open-im-server/v3/pkg/common/ginprometheus" import ginprom "github.com/openimsdk/open-im-server/v3/pkg/common/ginprometheus"
/* /*
labels := prometheus.Labels{"label_one": "any", "label_two": "value"} labels := prometheus.Labels{"label_one": "any", "label_two": "value"}
ApiCustomCnt.MetricCollector.(*prometheus.CounterVec).With(labels).Inc(). ApiCustomCnt.MetricCollector.(*prometheus.CounterVec).With(labels).Inc().
*/ */
var ( var (
ApiCustomCnt = &ginProm.Metric{ ApiCustomCnt = &ginprom.Metric{
Name: "custom_total", Name: "custom_total",
Description: "Custom counter events.", Description: "Custom counter events.",
Type: "counter_vec", Type: "counter_vec",
+3 -3
View File
@@ -15,7 +15,7 @@
package prommetrics package prommetrics
import ( import (
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus" gp "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/collectors"
@@ -23,10 +23,10 @@ import (
"github.com/openimsdk/open-im-server/v3/pkg/common/ginprometheus" "github.com/openimsdk/open-im-server/v3/pkg/common/ginprometheus"
) )
func NewGrpcPromObj(cusMetrics []prometheus.Collector) (*prometheus.Registry, *grpc_prometheus.ServerMetrics, error) { func NewGrpcPromObj(cusMetrics []prometheus.Collector) (*prometheus.Registry, *gp.ServerMetrics, error) {
//////////////////////////////////////////////////////// ////////////////////////////////////////////////////////
reg := prometheus.NewRegistry() reg := prometheus.NewRegistry()
grpcMetrics := grpc_prometheus.NewServerMetrics() grpcMetrics := gp.NewServerMetrics()
grpcMetrics.EnableHandlingTimeHistogram() grpcMetrics.EnableHandlingTimeHistogram()
cusMetrics = append(cusMetrics, grpcMetrics, collectors.NewGoCollector()) cusMetrics = append(cusMetrics, grpcMetrics, collectors.NewGoCollector())
reg.MustRegister(cusMetrics...) reg.MustRegister(cusMetrics...)
+1
View File
@@ -52,6 +52,7 @@ func GetChatConversationIDByMsg(msg *sdkws.MsgData) string {
case constant.NotificationChatType: case constant.NotificationChatType:
return "sn_" + msg.SendID + "_" + msg.RecvID return "sn_" + msg.SendID + "_" + msg.RecvID
} }
return "" return ""
} }
+1
View File
@@ -37,6 +37,7 @@ func NewOptions(opts ...OptionsOpt) Options {
for _, opt := range opts { for _, opt := range opts {
opt(options) opt(options)
} }
return options return options
} }
+18
View File
@@ -103,3 +103,21 @@ func (u *UserNotificationSender) UserStatusChangeNotification(
) error { ) error {
return u.Notification(ctx, tips.FromUserID, tips.ToUserID, constant.UserStatusChangeNotification, tips) return u.Notification(ctx, tips.FromUserID, tips.ToUserID, constant.UserStatusChangeNotification, tips)
} }
func (u *UserNotificationSender) UserCommandUpdateNotification(
ctx context.Context,
tips *sdkws.UserCommandUpdateTips,
) error {
return u.Notification(ctx, tips.FromUserID, tips.ToUserID, constant.UserCommandUpdateNotification, tips)
}
func (u *UserNotificationSender) UserCommandAddNotification(
ctx context.Context,
tips *sdkws.UserCommandAddTips,
) error {
return u.Notification(ctx, tips.FromUserID, tips.ToUserID, constant.UserCommandAddNotification, tips)
}
func (u *UserNotificationSender) UserCommandDeleteNotification(
ctx context.Context,
tips *sdkws.UserCommandDeleteTips,
) error {
return u.Notification(ctx, tips.FromUserID, tips.ToUserID, constant.UserCommandDeleteNotification, tips)
}
+40
View File
@@ -0,0 +1,40 @@
package flag
import (
goFlag "flag"
"log"
"strings"
"github.com/spf13/pflag"
)
// WordSepNormalizeFunc changes all flags that contain "_" separators.
func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
if strings.Contains(name, "_") {
return pflag.NormalizedName(strings.ReplaceAll(name, "_", "-"))
}
return pflag.NormalizedName(name)
}
// WarnWordSepNormalizeFunc changes and warns for flags that contain "_" separators.
func WarnWordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
if strings.Contains(name, "_") {
normalizedName := strings.ReplaceAll(name, "_", "-")
log.Printf("WARNING: flag %s has been deprecated and will be removed in a future version. Use %s instead.", name, normalizedName)
return pflag.NormalizedName(normalizedName)
}
return pflag.NormalizedName(name)
}
// InitFlags normalizes, parses, then logs the command line flags.
func InitFlags() {
pflag.CommandLine.SetNormalizeFunc(WordSepNormalizeFunc)
pflag.CommandLine.AddGoFlagSet(goFlag.CommandLine)
}
// PrintFlags logs the flags in the flagset.
func PrintFlags(flags *pflag.FlagSet) {
flags.VisitAll(func(flag *pflag.Flag) {
log.Printf("FLAG: --%s=%q", flag.Name, flag.Value)
})
}
+27
View File
@@ -0,0 +1,27 @@
package genutil
import (
"fmt"
"os"
"path/filepath"
)
// OutDir creates the absolute path name from path and checks path exists.
// Returns absolute path including trailing '/' or error if path does not exist.
func OutDir(path string) (string, error) {
outDir, err := filepath.Abs(path)
if err != nil {
return "", err
}
stat, err := os.Stat(outDir)
if err != nil {
return "", err
}
if !stat.IsDir() {
return "", fmt.Errorf("output directory %s is not a directory", outDir)
}
outDir += "/"
return outDir, nil
}
+26
View File
@@ -0,0 +1,26 @@
package genutil
import (
"testing"
)
func TestValidDir(t *testing.T) {
_, err := OutDir("./")
if err != nil {
t.Fatal(err)
}
}
func TestInvalidDir(t *testing.T) {
_, err := OutDir("./nondir")
if err == nil {
t.Fatal("expected an error")
}
}
func TestNotDir(t *testing.T) {
_, err := OutDir("./genutils_test.go")
if err == nil {
t.Fatal("expected an error")
}
}
+45 -45
View File
@@ -23,7 +23,7 @@ trap 'openim::util::onCtrlC' INT
print_with_delay() { print_with_delay() {
text="$1" text="$1"
delay="$2" delay="$2"
for i in $(seq 0 $((${#text}-1))); do for i in $(seq 0 $((${#text}-1))); do
printf "${text:$i:1}" printf "${text:$i:1}"
sleep $delay sleep $delay
@@ -34,7 +34,7 @@ print_with_delay() {
print_progress() { print_progress() {
total="$1" total="$1"
delay="$2" delay="$2"
printf "[" printf "["
for i in $(seq 1 $total); do for i in $(seq 1 $total); do
printf "#" printf "#"
@@ -44,14 +44,14 @@ print_progress() {
} }
function openim_logo() { function openim_logo() {
# Set text color to cyan for header and URL # Set text color to cyan for header and URL
echo -e "\033[0;36m" echo -e "\033[0;36m"
# Display fancy ASCII Art logo
# look http://patorjk.com/software/taag/#p=display&h=1&v=1&f=Doh&t=OpenIM
print_with_delay '
# Display fancy ASCII Art logo
# look http://patorjk.com/software/taag/#p=display&h=1&v=1&f=Doh&t=OpenIM
print_with_delay '
OOOOOOOOO IIIIIIIIIIMMMMMMMM MMMMMMMM OOOOOOOOO IIIIIIIIIIMMMMMMMM MMMMMMMM
OO:::::::::OO I::::::::IM:::::::M M:::::::M OO:::::::::OO I::::::::IM:::::::M M:::::::M
OO:::::::::::::OO I::::::::IM::::::::M M::::::::M OO:::::::::::::OO I::::::::IM::::::::M M::::::::M
@@ -68,45 +68,45 @@ O:::::::OOO:::::::O p:::::ppppp:::::::pe::::::::e n::::n n::::nII:
OO:::::::::::::OO p::::::::::::::::p e::::::::eeeeeeee n::::n n::::nI::::::::IM::::::M M::::::M OO:::::::::::::OO p::::::::::::::::p e::::::::eeeeeeee n::::n n::::nI::::::::IM::::::M M::::::M
OO:::::::::OO p::::::::::::::pp ee:::::::::::::e n::::n n::::nI::::::::IM::::::M M::::::M OO:::::::::OO p::::::::::::::pp ee:::::::::::::e n::::n n::::nI::::::::IM::::::M M::::::M
OOOOOOOOO p::::::pppppppp eeeeeeeeeeeeee nnnnnn nnnnnnIIIIIIIIIIMMMMMMMM MMMMMMMM OOOOOOOOO p::::::pppppppp eeeeeeeeeeeeee nnnnnn nnnnnnIIIIIIIIIIMMMMMMMM MMMMMMMM
p:::::p p:::::p
p:::::p p:::::p
p:::::::p p:::::::p
p:::::::p p:::::::p
p:::::::p p:::::::p
ppppppppp ppppppppp
' 0.0001
' 0.0001 # Display product URL
print_with_delay "Discover more and contribute at: https://github.com/openimsdk/open-im-server" 0.01
# Display product URL
print_with_delay "Discover more and contribute at: https://github.com/openimsdk/open-im-server" 0.01 # Reset text color back to normal
echo -e "\033[0m"
# Reset text color back to normal
echo -e "\033[0m" # Set text color to green for product description
echo -e "\033[1;32m"
# Set text color to green for product description
echo -e "\033[1;32m" print_with_delay "Open-IM-Server: Reinventing Instant Messaging" 0.01
print_progress 50 0.02
print_with_delay "Open-IM-Server: Reinventing Instant Messaging" 0.01
print_progress 50 0.02 print_with_delay "Open-IM-Server is not just a product; it's a revolution. It's about bringing the power of seamless," 0.01
print_with_delay "real-time messaging to your fingertips. And it's about joining a global community of developers, dedicated to pushing the boundaries of what's possible." 0.01
print_with_delay "Open-IM-Server is not just a product; it's a revolution. It's about bringing the power of seamless," 0.01
print_with_delay "real-time messaging to your fingertips. And it's about joining a global community of developers, dedicated to pushing the boundaries of what's possible." 0.01 print_progress 50 0.02
print_progress 50 0.02 # Reset text color back to normal
echo -e "\033[0m"
# Reset text color back to normal
echo -e "\033[0m" # Set text color to yellow for the Slack link
echo -e "\033[1;33m"
# Set text color to yellow for the Slack link
echo -e "\033[1;33m" print_with_delay "Join our developer community on Slack: https://join.slack.com/t/openimsdk/shared_invite/zt-22720d66b-o_FvKxMTGXtcnnnHiMqe9Q" 0.01
print_with_delay "Join our developer community on Slack: https://join.slack.com/t/openimsdk/shared_invite/zt-22720d66b-o_FvKxMTGXtcnnnHiMqe9Q" 0.01 # Reset text color back to normal
echo -e "\033[0m"
# Reset text color back to normal
echo -e "\033[0m"
} }
function main() { function main() {
openim_logo openim_logo
} }
main "$@" main "$@"
-173
View File
@@ -1,173 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#**************************************************************************
# Copyright (C) 2011, Paul Lutus *
# *
# This program is free software; you can redistribute it and/or modify *
# it under the terms of the GNU General Public License as published by *
# the Free Software Foundation; either version 2 of the License, or *
# (at your option) any later version. *
# *
# This program is distributed in the hope that it will be useful, *
# but WITHOUT ANY WARRANTY; without even the implied warranty of *
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# GNU General Public License for more details. *
# *
# You should have received a copy of the GNU General Public License *
# along with this program; if not, write to the *
# Free Software Foundation, Inc., *
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
#**************************************************************************
import re
import sys
PVERSION = '1.0'
class BeautifyBash:
def __init__(self):
self.tab_str = ' '
self.tab_size = 2
def read_file(self, fp):
with open(fp) as f:
return f.read()
def write_file(self, fp, data):
with open(fp, 'w') as f:
f.write(data)
def beautify_string(self, data, path=''):
tab = 0
case_stack = []
in_here_doc = False
defer_ext_quote = False
in_ext_quote = False
ext_quote_string = ''
here_string = ''
output = []
line = 1
for record in re.split('\n', data):
record = record.rstrip()
stripped_record = record.strip()
# collapse multiple quotes between ' ... '
test_record = re.sub(r'\'.*?\'', '', stripped_record)
# collapse multiple quotes between " ... "
test_record = re.sub(r'".*?"', '', test_record)
# collapse multiple quotes between ` ... `
test_record = re.sub(r'`.*?`', '', test_record)
# collapse multiple quotes between \` ... ' (weird case)
test_record = re.sub(r'\\`.*?\'', '', test_record)
# strip out any escaped single characters
test_record = re.sub(r'\\.', '', test_record)
# remove '#' comments
test_record = re.sub(r'(\A|\s)(#.*)', '', test_record, 1)
if(not in_here_doc):
if(re.search('<<-?', test_record)):
here_string = re.sub(
'.*<<-?\s*[\'|"]?([_|\w]+)[\'|"]?.*', '\\1', stripped_record, 1)
in_here_doc = (len(here_string) > 0)
if(in_here_doc): # pass on with no changes
output.append(record)
# now test for here-doc termination string
if(re.search(here_string, test_record) and not re.search('<<', test_record)):
in_here_doc = False
else: # not in here doc
if(in_ext_quote):
if(re.search(ext_quote_string, test_record)):
# provide line after quotes
test_record = re.sub(
'.*%s(.*)' % ext_quote_string, '\\1', test_record, 1)
in_ext_quote = False
else: # not in ext quote
if(re.search(r'(\A|\s)(\'|")', test_record)):
# apply only after this line has been processed
defer_ext_quote = True
ext_quote_string = re.sub(
'.*([\'"]).*', '\\1', test_record, 1)
# provide line before quote
test_record = re.sub(
'(.*)%s.*' % ext_quote_string, '\\1', test_record, 1)
if(in_ext_quote):
# pass on unchanged
output.append(record)
else: # not in ext quote
inc = len(re.findall(
'(\s|\A|;)(case|then|do)(;|\Z|\s)', test_record))
inc += len(re.findall('(\{|\(|\[)', test_record))
outc = len(re.findall(
'(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)', test_record))
outc += len(re.findall('(\}|\)|\])', test_record))
if(re.search(r'\besac\b', test_record)):
if(len(case_stack) == 0):
sys.stderr.write(
'File %s: error: "esac" before "case" in line %d.\n' % (
path, line)
)
else:
outc += case_stack.pop()
# sepcial handling for bad syntax within case ... esac
if(len(case_stack) > 0):
if(re.search('\A[^(]*\)', test_record)):
# avoid overcount
outc -= 2
case_stack[-1] += 1
if(re.search(';;', test_record)):
outc += 1
case_stack[-1] -= 1
# an ad-hoc solution for the "else" keyword
else_case = (
0, -1)[re.search('^(else)', test_record) != None]
net = inc - outc
tab += min(net, 0)
extab = tab + else_case
extab = max(0, extab)
output.append(
(self.tab_str * self.tab_size * extab) + stripped_record)
tab += max(net, 0)
if(defer_ext_quote):
in_ext_quote = True
defer_ext_quote = False
if(re.search(r'\bcase\b', test_record)):
case_stack.append(0)
line += 1
error = (tab != 0)
if(error):
sys.stderr.write(
'File %s: error: indent/outdent mismatch: %d.\n' % (path, tab))
return '\n'.join(output), error
def beautify_file(self, path):
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(path)
result, error = self.beautify_string(data, path)
if(data != result):
# make a backup copy
self.write_file(path + '~', data)
self.write_file(path, result)
return error
def main(self):
error = False
sys.argv.pop(0)
if(len(sys.argv) < 1):
sys.stderr.write(
'usage: shell script filenames or \"-\" for stdin.\n')
else:
for path in sys.argv:
error |= self.beautify_file(path)
sys.exit((0, 1)[error])
# if not called as a module
if(__name__ == '__main__'):
BeautifyBash().main()
+8 -8
View File
@@ -31,7 +31,7 @@ source "${OPENIM_ROOT}/scripts/lib/init.sh"
# CPU core number # CPU core number
pushd "${OPENIM_ROOT}/tools/ncpu" >/dev/null pushd "${OPENIM_ROOT}/tools/ncpu" >/dev/null
cpu_count=$(go run .) cpu_count=$(go run .)
popd >/dev/null popd >/dev/null
openim::color::echo ${GREEN_PREFIX} "======> cpu_count=$cpu_count" openim::color::echo ${GREEN_PREFIX} "======> cpu_count=$cpu_count"
@@ -42,7 +42,7 @@ compile_count=$((cpu_count / 2))
# For help output # For help output
ARGHELP="" ARGHELP=""
if [[ "$#" -gt 0 ]]; then if [[ "$#" -gt 0 ]]; then
ARGHELP="'$*'" ARGHELP="'$*'"
fi fi
openim::color::echo $COLOR_CYAN "NOTE: $0 has been replaced by 'make multiarch' or 'make build'" openim::color::echo $COLOR_CYAN "NOTE: $0 has been replaced by 'make multiarch' or 'make build'"
@@ -61,15 +61,15 @@ echo " ./scripts/build-all-service.sh BINS=openim-api V=1 DEBUG=1"
echo echo
if [ -z "$*" ]; then if [ -z "$*" ]; then
openim::log::info "no args, build all service" openim::log::info "no args, build all service"
make --no-print-directory -C "${OPENIM_ROOT}" -j$compile_count build make --no-print-directory -C "${OPENIM_ROOT}" -j$compile_count build
else else
openim::log::info "build service: $*" openim::log::info "build service: $*"
make --no-print-directory -C "${OPENIM_ROOT}" -j$compile_count build "$*" make --no-print-directory -C "${OPENIM_ROOT}" -j$compile_count build "$*"
fi fi
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
openim::log::success "all service build success, run 'make start' or './scripts/start-all.sh'" openim::log::success "all service build success, run 'make start' or './scripts/start-all.sh'"
else else
openim::log::error "make build Error, script exits" openim::log::error "make build Error, script exits"
fi fi
+18 -18
View File
@@ -14,10 +14,10 @@
# limitations under the License. # limitations under the License.
# This script is check openim service is running normally # This script is check openim service is running normally
# #
# Usage: `scripts/check-all.sh`. # Usage: `scripts/check-all.sh`.
# Encapsulated as: `make check`. # Encapsulated as: `make check`.
# READ: https://github.com/openimsdk/open-im-server/tree/main/scripts/install/environment.sh # READ: https://github.com/openimsdk/open-im-server/tree/main/scripts/install/environment.sh
set -o errexit set -o errexit
set -o nounset set -o nounset
@@ -34,19 +34,19 @@ openim::log::status "Check all dependent service ports"
# Elegant printing function # Elegant printing function
# Elegant printing function # Elegant printing function
print_services_and_ports() { print_services_and_ports() {
local service_names=("$@") local service_names=("$@")
local half_length=$((${#service_names[@]} / 2)) local half_length=$((${#service_names[@]} / 2))
local service_ports=("${service_names[@]:half_length}") local service_ports=("${service_names[@]:half_length}")
echo "+-------------------------+----------+" echo "+-------------------------+----------+"
echo "| Service Name | Port |" echo "| Service Name | Port |"
echo "+-------------------------+----------+" echo "+-------------------------+----------+"
for ((index=0; index < half_length; index++)); do for ((index=0; index < half_length; index++)); do
printf "| %-23s | %-8s |\n" "${service_names[$index]}" "${service_ports[$index]}" printf "| %-23s | %-8s |\n" "${service_names[$index]}" "${service_ports[$index]}"
done done
echo "+-------------------------+----------+" echo "+-------------------------+----------+"
} }
# Assuming OPENIM_SERVER_NAME_TARGETS and OPENIM_SERVER_PORT_TARGETS are defined # Assuming OPENIM_SERVER_NAME_TARGETS and OPENIM_SERVER_PORT_TARGETS are defined
@@ -67,10 +67,10 @@ set +e
# Later, after discarding Docker, the Docker keyword is unreliable, and Kubepods is used # Later, after discarding Docker, the Docker keyword is unreliable, and Kubepods is used
if grep -qE 'docker|kubepods' /proc/1/cgroup || [ -f /.dockerenv ]; then if grep -qE 'docker|kubepods' /proc/1/cgroup || [ -f /.dockerenv ]; then
openim::color::echo ${COLOR_CYAN} "Environment in the interior of the container" openim::color::echo ${COLOR_CYAN} "Environment in the interior of the container"
else else
openim::color::echo ${COLOR_CYAN} "The environment is outside the container" openim::color::echo ${COLOR_CYAN} "The environment is outside the container"
openim::util::check_ports ${OPENIM_DEPENDENCY_PORT_LISTARIES[@]} || return 0 openim::util::check_ports ${OPENIM_DEPENDENCY_PORT_LISTARIES[@]} || return 0
fi fi
if [[ $? -ne 0 ]]; then if [[ $? -ne 0 ]]; then
+66 -66
View File
@@ -118,7 +118,7 @@ function return_to_kansas {
openim::log::status "Aborting in-progress git am." openim::log::status "Aborting in-progress git am."
git am --abort >/dev/null 2>&1 || true git am --abort >/dev/null 2>&1 || true
fi fi
# return to the starting branch and delete the PR text file # return to the starting branch and delete the PR text file
if [[ -z "${DRY_RUN}" ]]; then if [[ -z "${DRY_RUN}" ]]; then
echo echo
@@ -137,7 +137,7 @@ function make-a-pr() {
rel="$(basename "${BRANCH}")" rel="$(basename "${BRANCH}")"
echo echo
openim::log::status "Creating a pull request on GitHub at ${GITHUB_USER}:${NEWBRANCH}" openim::log::status "Creating a pull request on GitHub at ${GITHUB_USER}:${NEWBRANCH}"
local numandtitle local numandtitle
numandtitle=$(printf '%s\n' "${SUBJECTS[@]}") numandtitle=$(printf '%s\n' "${SUBJECTS[@]}")
prtext=$(cat <<EOF prtext=$(cat <<EOF
@@ -153,7 +153,7 @@ For details on the cherry pick process, see the [cherry pick requests](https://g
EOF EOF
) )
gh pr create --title="Automated cherry pick of ${numandtitle}" --body="${prtext}" --head "${GITHUB_USER}:${NEWBRANCH}" --base "${rel}" --repo="${MAIN_REPO_ORG}/${MAIN_REPO_NAME}" gh pr create --title="Automated cherry pick of ${numandtitle}" --body="${prtext}" --head "${GITHUB_USER}:${NEWBRANCH}" --base "${rel}" --repo="${MAIN_REPO_ORG}/${MAIN_REPO_NAME}"
} }
git checkout -b "${NEWBRANCHUNIQ}" "${BRANCH}" git checkout -b "${NEWBRANCHUNIQ}" "${BRANCH}"
@@ -161,84 +161,84 @@ cleanbranch="${NEWBRANCHUNIQ}"
gitamcleanup=true gitamcleanup=true
for pull in "${PULLS[@]}"; do for pull in "${PULLS[@]}"; do
openim::log::status "Downloading patch to /tmp/${pull}.patch (in case you need to do this again)" openim::log::status "Downloading patch to /tmp/${pull}.patch (in case you need to do this again)"
curl -o "/tmp/${pull}.patch" -sSL "https://github.com/${MAIN_REPO_ORG}/${MAIN_REPO_NAME}/pull/${pull}.patch" curl -o "/tmp/${pull}.patch" -sSL "https://github.com/${MAIN_REPO_ORG}/${MAIN_REPO_NAME}/pull/${pull}.patch"
echo echo
openim::log::status "About to attempt cherry pick of PR. To reattempt:" openim::log::status "About to attempt cherry pick of PR. To reattempt:"
echo " $ git am -3 /tmp/${pull}.patch" echo " $ git am -3 /tmp/${pull}.patch"
echo echo
git am -3 "/tmp/${pull}.patch" || { git am -3 "/tmp/${pull}.patch" || {
conflicts=false conflicts=false
while unmerged=$(git status --porcelain | grep ^U) && [[ -n ${unmerged} ]] \ while unmerged=$(git status --porcelain | grep ^U) && [[ -n ${unmerged} ]] \
|| [[ -e "${REBASEMAGIC}" ]]; do || [[ -e "${REBASEMAGIC}" ]]; do
conflicts=true # <-- We should have detected conflicts once conflicts=true # <-- We should have detected conflicts once
echo echo
openim::log::status "Conflicts detected:" openim::log::status "Conflicts detected:"
echo echo
(git status --porcelain | grep ^U) || echo "!!! None. Did you git am --continue?" (git status --porcelain | grep ^U) || echo "!!! None. Did you git am --continue?"
echo echo
openim::log::status "Please resolve the conflicts in another window (and remember to 'git add / git am --continue')" openim::log::status "Please resolve the conflicts in another window (and remember to 'git add / git am --continue')"
read -p "+++ Proceed (anything other than 'y' aborts the cherry-pick)? [y/n] " -r read -p "+++ Proceed (anything other than 'y' aborts the cherry-pick)? [y/n] " -r
echo echo
if ! [[ "${REPLY}" =~ ^[yY]$ ]]; then if ! [[ "${REPLY}" =~ ^[yY]$ ]]; then
echo "Aborting." >&2 echo "Aborting." >&2
exit 1
fi
done
if [[ "${conflicts}" != "true" ]]; then
echo "!!! git am failed, likely because of an in-progress 'git am' or 'git rebase'"
exit 1 exit 1
fi fi
done }
if [[ "${conflicts}" != "true" ]]; then
echo "!!! git am failed, likely because of an in-progress 'git am' or 'git rebase'"
exit 1
fi
}
# set the subject # set the subject
subject=$(grep -m 1 "^Subject" "/tmp/${pull}.patch" | sed -e 's/Subject: \[PATCH//g' | sed 's/.*] //') subject=$(grep -m 1 "^Subject" "/tmp/${pull}.patch" | sed -e 's/Subject: \[PATCH//g' | sed 's/.*] //')
SUBJECTS+=("#${pull}: ${subject}") SUBJECTS+=("#${pull}: ${subject}")
# remove the patch file from /tmp # remove the patch file from /tmp
rm -f "/tmp/${pull}.patch" rm -f "/tmp/${pull}.patch"
done done
gitamcleanup=false gitamcleanup=false
# Re-generate docs (if needed) # Re-generate docs (if needed)
if [[ -n "${REGENERATE_DOCS}" ]]; then if [[ -n "${REGENERATE_DOCS}" ]]; then
echo
echo "Regenerating docs..."
if ! scripts/generate-docs.sh; then
echo echo
echo "scripts/gendoc.sh FAILED to complete." echo "Regenerating docs..."
exit 1 if ! scripts/generate-docs.sh; then
fi echo
echo "scripts/gendoc.sh FAILED to complete."
exit 1
fi
fi fi
if [[ -n "${DRY_RUN}" ]]; then if [[ -n "${DRY_RUN}" ]]; then
openim::log::error "!!! Skipping git push and PR creation because you set DRY_RUN." openim::log::error "!!! Skipping git push and PR creation because you set DRY_RUN."
echo "To return to the branch you were in when you invoked this script:" echo "To return to the branch you were in when you invoked this script:"
echo echo
echo " git checkout ${STARTINGBRANCH}" echo " git checkout ${STARTINGBRANCH}"
echo echo
echo "To delete this branch:" echo "To delete this branch:"
echo echo
echo " git branch -D ${NEWBRANCHUNIQ}" echo " git branch -D ${NEWBRANCHUNIQ}"
exit 0 exit 0
fi fi
if git remote -v | grep ^"${FORK_REMOTE}" | grep "${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git"; then if git remote -v | grep ^"${FORK_REMOTE}" | grep "${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git"; then
echo "!!! You have ${FORK_REMOTE} configured as your ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git" echo "!!! You have ${FORK_REMOTE} configured as your ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git"
echo "This isn't normal. Leaving you with push instructions:" echo "This isn't normal. Leaving you with push instructions:"
echo echo
openim::log::status "First manually push the branch this script created:" openim::log::status "First manually push the branch this script created:"
echo echo
echo " git push REMOTE ${NEWBRANCHUNIQ}:${NEWBRANCH}" echo " git push REMOTE ${NEWBRANCHUNIQ}:${NEWBRANCH}"
echo echo
echo "where REMOTE is your personal fork (maybe ${UPSTREAM_REMOTE}? Consider swapping those.)." echo "where REMOTE is your personal fork (maybe ${UPSTREAM_REMOTE}? Consider swapping those.)."
echo "OR consider setting UPSTREAM_REMOTE and FORK_REMOTE to different values." echo "OR consider setting UPSTREAM_REMOTE and FORK_REMOTE to different values."
echo echo
make-a-pr make-a-pr
cleanbranch="" cleanbranch=""
exit 0 exit 0
fi fi
echo echo
@@ -248,8 +248,8 @@ echo " git push ${FORK_REMOTE} ${NEWBRANCHUNIQ}:${NEWBRANCH}"
echo echo
read -p "+++ Proceed (anything other than 'y' aborts the cherry-pick)? [y/n] " -r read -p "+++ Proceed (anything other than 'y' aborts the cherry-pick)? [y/n] " -r
if ! [[ "${REPLY}" =~ ^[yY]$ ]]; then if ! [[ "${REPLY}" =~ ^[yY]$ ]]; then
echo "Aborting." >&2 echo "Aborting." >&2
exit 1 exit 1
fi fi
git push "${FORK_REMOTE}" -f "${NEWBRANCHUNIQ}:${NEWBRANCH}" git push "${FORK_REMOTE}" -f "${NEWBRANCHUNIQ}:${NEWBRANCH}"
+281 -281
View File
@@ -87,28 +87,28 @@ readonly OPENIM_CONTAINER_RSYNC_PORT=8730
# #
# $1 - server architecture # $1 - server architecture
openim::build::get_docker_wrapped_binaries() { openim::build::get_docker_wrapped_binaries() {
local arch=$1 local arch=$1
local debian_base_version=v2.1.0 local debian_base_version=v2.1.0
local debian_iptables_version=v12.1.0 local debian_iptables_version=v12.1.0
### If you change any of these lists, please also update DOCKERIZED_BINARIES ### If you change any of these lists, please also update DOCKERIZED_BINARIES
### in build/BUILD. And openim::golang::server_image_targets ### in build/BUILD. And openim::golang::server_image_targets
local targets=( local targets=(
"openim-api,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-api,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-cmdutils,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-cmdutils,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-crontask,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-crontask,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-msggateway,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-msggateway,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-msgtransfer,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-msgtransfer,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-push,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-push,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-auth,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-auth,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-conversation,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-conversation,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-friend,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-friend,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-group,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-group,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-msg,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-msg,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-third,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-third,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
"openim-rpc-user,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}" "openim-rpc-user,${OPENIM_BASE_IMAGE_REGISTRY}/debian-base-${arch}:${debian_base_version}"
) )
echo "${targets[@]}" echo "${targets[@]}"
} }
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -133,170 +133,170 @@ echo "${targets[@]}"
# DOCKER_MOUNT_ARGS # DOCKER_MOUNT_ARGS
# LOCAL_OUTPUT_BUILD_CONTEXT # LOCAL_OUTPUT_BUILD_CONTEXT
function openim::build::verify_prereqs() { function openim::build::verify_prereqs() {
local -r require_docker=${1:-true} local -r require_docker=${1:-true}
openim::log::status "Verifying Prerequisites...." openim::log::status "Verifying Prerequisites...."
openim::build::ensure_tar || return 1 openim::build::ensure_tar || return 1
openim::build::ensure_rsync || return 1 openim::build::ensure_rsync || return 1
if ${require_docker}; then if ${require_docker}; then
openim::build::ensure_docker_in_path || return 1 openim::build::ensure_docker_in_path || return 1
openim::util::ensure_docker_daemon_connectivity || return 1 openim::util::ensure_docker_daemon_connectivity || return 1
if (( OPENIM_VERBOSE > 6 )); then if (( OPENIM_VERBOSE > 6 )); then
openim::log::status "Docker Version:" openim::log::status "Docker Version:"
"${DOCKER[@]}" version | openim::log::info_from_stdin "${DOCKER[@]}" version | openim::log::info_from_stdin
fi
fi fi
fi
OPENIM_GIT_BRANCH=$(git symbolic-ref --short -q HEAD 2>/dev/null || true) OPENIM_GIT_BRANCH=$(git symbolic-ref --short -q HEAD 2>/dev/null || true)
OPENIM_ROOT_HASH=$(openim::build::short_hash "${HOSTNAME:-}:${OPENIM_ROOT}:${OPENIM_GIT_BRANCH}") OPENIM_ROOT_HASH=$(openim::build::short_hash "${HOSTNAME:-}:"${OPENIM_ROOT}":${OPENIM_GIT_BRANCH}")
OPENIM_BUILD_IMAGE_TAG_BASE="build-${OPENIM_ROOT_HASH}" OPENIM_BUILD_IMAGE_TAG_BASE="build-${OPENIM_ROOT_HASH}"
#OPENIM_BUILD_IMAGE_TAG="${OPENIM_BUILD_IMAGE_TAG_BASE}-${OPENIM_BUILD_IMAGE_VERSION}" #OPENIM_BUILD_IMAGE_TAG="${OPENIM_BUILD_IMAGE_TAG_BASE}-${OPENIM_BUILD_IMAGE_VERSION}"
#OPENIM_BUILD_IMAGE="${OPENIM_BUILD_IMAGE_REPO}:${OPENIM_BUILD_IMAGE_TAG}" #OPENIM_BUILD_IMAGE="${OPENIM_BUILD_IMAGE_REPO}:${OPENIM_BUILD_IMAGE_TAG}"
OPENIM_BUILD_CONTAINER_NAME_BASE="openim-build-${OPENIM_ROOT_HASH}" OPENIM_BUILD_CONTAINER_NAME_BASE="openim-build-${OPENIM_ROOT_HASH}"
#OPENIM_BUILD_CONTAINER_NAME="${OPENIM_BUILD_CONTAINER_NAME_BASE}-${OPENIM_BUILD_IMAGE_VERSION}" #OPENIM_BUILD_CONTAINER_NAME="${OPENIM_BUILD_CONTAINER_NAME_BASE}-${OPENIM_BUILD_IMAGE_VERSION}"
OPENIM_RSYNC_CONTAINER_NAME_BASE="openim-rsync-${OPENIM_ROOT_HASH}" OPENIM_RSYNC_CONTAINER_NAME_BASE="openim-rsync-${OPENIM_ROOT_HASH}"
#OPENIM_RSYNC_CONTAINER_NAME="${OPENIM_RSYNC_CONTAINER_NAME_BASE}-${OPENIM_BUILD_IMAGE_VERSION}" #OPENIM_RSYNC_CONTAINER_NAME="${OPENIM_RSYNC_CONTAINER_NAME_BASE}-${OPENIM_BUILD_IMAGE_VERSION}"
OPENIM_DATA_CONTAINER_NAME_BASE="openim-build-data-${OPENIM_ROOT_HASH}" OPENIM_DATA_CONTAINER_NAME_BASE="openim-build-data-${OPENIM_ROOT_HASH}"
#OPENIM_DATA_CONTAINER_NAME="${OPENIM_DATA_CONTAINER_NAME_BASE}-${OPENIM_BUILD_IMAGE_VERSION}" #OPENIM_DATA_CONTAINER_NAME="${OPENIM_DATA_CONTAINER_NAME_BASE}-${OPENIM_BUILD_IMAGE_VERSION}"
#DOCKER_MOUNT_ARGS=(--volumes-from "${OPENIM_DATA_CONTAINER_NAME}") #DOCKER_MOUNT_ARGS=(--volumes-from "${OPENIM_DATA_CONTAINER_NAME}")
#LOCAL_OUTPUT_BUILD_CONTEXT="${LOCAL_OUTPUT_IMAGE_STAGING}/${OPENIM_BUILD_IMAGE}" #LOCAL_OUTPUT_BUILD_CONTEXT="${LOCAL_OUTPUT_IMAGE_STAGING}/${OPENIM_BUILD_IMAGE}"
openim::version::get_version_vars openim::version::get_version_vars
#openim::version::save_version_vars "${OPENIM_ROOT}/.dockerized-openim-version-defs" #openim::version::save_version_vars "${OPENIM_ROOT}/.dockerized-openim-version-defs"
} }
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Utility functions # Utility functions
function openim::build::docker_available_on_osx() { function openim::build::docker_available_on_osx() {
if [[ -z "${DOCKER_HOST}" ]]; then if [[ -z "${DOCKER_HOST}" ]]; then
if [[ -S "/var/run/docker.sock" ]]; then if [[ -S "/var/run/docker.sock" ]]; then
openim::log::status "Using Docker for MacOS" openim::log::status "Using Docker for MacOS"
return 0 return 0
fi fi
openim::log::status "No docker host is set. Checking options for setting one..." openim::log::status "No docker host is set. Checking options for setting one..."
if [[ -z "$(which docker-machine)" ]]; then if [[ -z "$(which docker-machine)" ]]; then
openim::log::status "It looks like you're running Mac OS X, yet neither Docker for Mac nor docker-machine can be found." openim::log::status "It looks like you're running Mac OS X, yet neither Docker for Mac nor docker-machine can be found."
openim::log::status "See: https://docs.docker.com/engine/installation/mac/ for installation instructions." openim::log::status "See: https://docs.docker.com/engine/installation/mac/ for installation instructions."
return 1 return 1
elif [[ -n "$(which docker-machine)" ]]; then elif [[ -n "$(which docker-machine)" ]]; then
openim::build::prepare_docker_machine openim::build::prepare_docker_machine
fi
fi fi
fi
} }
function openim::build::prepare_docker_machine() { function openim::build::prepare_docker_machine() {
openim::log::status "docker-machine was found." openim::log::status "docker-machine was found."
local available_memory_bytes local available_memory_bytes
available_memory_bytes=$(sysctl -n hw.memsize 2>/dev/null) available_memory_bytes=$(sysctl -n hw.memsize 2>/dev/null)
local bytes_in_mb=1048576 local bytes_in_mb=1048576
# Give virtualbox 1/2 the system memory. Its necessary to divide by 2, instead # Give virtualbox 1/2 the system memory. Its necessary to divide by 2, instead
# of multiple by .5, because bash can only multiply by ints. # of multiple by .5, because bash can only multiply by ints.
local memory_divisor=2 local memory_divisor=2
local virtualbox_memory_mb=$(( available_memory_bytes / (bytes_in_mb * memory_divisor) )) local virtualbox_memory_mb=$(( available_memory_bytes / (bytes_in_mb * memory_divisor) ))
docker-machine inspect "${DOCKER_MACHINE_NAME}" &> /dev/null || { docker-machine inspect "${DOCKER_MACHINE_NAME}" &> /dev/null || {
openim::log::status "Creating a machine to build OPENIM" openim::log::status "Creating a machine to build OPENIM"
docker-machine create --driver "${DOCKER_MACHINE_DRIVER}" \ docker-machine create --driver "${DOCKER_MACHINE_DRIVER}" \
--virtualbox-memory "${virtualbox_memory_mb}" \ --virtualbox-memory "${virtualbox_memory_mb}" \
--engine-env HTTP_PROXY="${OPENIMRNETES_HTTP_PROXY:-}" \ --engine-env HTTP_PROXY="${OPENIMRNETES_HTTP_PROXY:-}" \
--engine-env HTTPS_PROXY="${OPENIMRNETES_HTTPS_PROXY:-}" \ --engine-env HTTPS_PROXY="${OPENIMRNETES_HTTPS_PROXY:-}" \
--engine-env NO_PROXY="${OPENIMRNETES_NO_PROXY:-127.0.0.1}" \ --engine-env NO_PROXY="${OPENIMRNETES_NO_PROXY:-127.0.0.1}" \
"${DOCKER_MACHINE_NAME}" > /dev/null || { "${DOCKER_MACHINE_NAME}" > /dev/null || {
openim::log::error "Something went wrong creating a machine." openim::log::error "Something went wrong creating a machine."
openim::log::error "Try the following: " openim::log::error "Try the following: "
openim::log::error "docker-machine create -d ${DOCKER_MACHINE_DRIVER} --virtualbox-memory ${virtualbox_memory_mb} ${DOCKER_MACHINE_NAME}" openim::log::error "docker-machine create -d ${DOCKER_MACHINE_DRIVER} --virtualbox-memory ${virtualbox_memory_mb} ${DOCKER_MACHINE_NAME}"
return 1 return 1
}
} }
} docker-machine start "${DOCKER_MACHINE_NAME}" &> /dev/null
docker-machine start "${DOCKER_MACHINE_NAME}" &> /dev/null # it takes `docker-machine env` a few seconds to work if the machine was just started
# it takes `docker-machine env` a few seconds to work if the machine was just started local docker_machine_out
local docker_machine_out while ! docker_machine_out=$(docker-machine env "${DOCKER_MACHINE_NAME}" 2>&1); do
while ! docker_machine_out=$(docker-machine env "${DOCKER_MACHINE_NAME}" 2>&1); do if [[ ${docker_machine_out} =~ "Error checking TLS connection" ]]; then
if [[ ${docker_machine_out} =~ "Error checking TLS connection" ]]; then echo "${docker_machine_out}"
echo "${docker_machine_out}" docker-machine regenerate-certs "${DOCKER_MACHINE_NAME}"
docker-machine regenerate-certs "${DOCKER_MACHINE_NAME}" else
else sleep 1
sleep 1 fi
fi done
done eval "$(docker-machine env "${DOCKER_MACHINE_NAME}")"
eval "$(docker-machine env "${DOCKER_MACHINE_NAME}")" openim::log::status "A Docker host using docker-machine named '${DOCKER_MACHINE_NAME}' is ready to go!"
openim::log::status "A Docker host using docker-machine named '${DOCKER_MACHINE_NAME}' is ready to go!" return 0
return 0
} }
function openim::build::is_gnu_sed() { function openim::build::is_gnu_sed() {
[[ $(sed --version 2>&1) == *GNU* ]] [[ $(sed --version 2>&1) == *GNU* ]]
} }
function openim::build::ensure_rsync() { function openim::build::ensure_rsync() {
if [[ -z "$(which rsync)" ]]; then if [[ -z "$(which rsync)" ]]; then
openim::log::error "Can't find 'rsync' in PATH, please fix and retry." openim::log::error "Can't find 'rsync' in PATH, please fix and retry."
return 1 return 1
fi fi
} }
function openim::build::update_dockerfile() { function openim::build::update_dockerfile() {
if openim::build::is_gnu_sed; then if openim::build::is_gnu_sed; then
sed_opts=(-i) sed_opts=(-i)
else else
sed_opts=(-i '') sed_opts=(-i '')
fi fi
sed "${sed_opts[@]}" "s/OPENIM_BUILD_IMAGE_CROSS_TAG/${OPENIM_BUILD_IMAGE_CROSS_TAG}/" "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile" sed "${sed_opts[@]}" "s/OPENIM_BUILD_IMAGE_CROSS_TAG/${OPENIM_BUILD_IMAGE_CROSS_TAG}/" "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile"
} }
function openim::build::set_proxy() { function openim::build::set_proxy() {
if [[ -n "${OPENIMRNETES_HTTPS_PROXY:-}" ]]; then if [[ -n "${OPENIMRNETES_HTTPS_PROXY:-}" ]]; then
echo "ENV https_proxy $OPENIMRNETES_HTTPS_PROXY" >> "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile" echo "ENV https_proxy $OPENIMRNETES_HTTPS_PROXY" >> "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile"
fi fi
if [[ -n "${OPENIMRNETES_HTTP_PROXY:-}" ]]; then if [[ -n "${OPENIMRNETES_HTTP_PROXY:-}" ]]; then
echo "ENV http_proxy $OPENIMRNETES_HTTP_PROXY" >> "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile" echo "ENV http_proxy $OPENIMRNETES_HTTP_PROXY" >> "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile"
fi fi
if [[ -n "${OPENIMRNETES_NO_PROXY:-}" ]]; then if [[ -n "${OPENIMRNETES_NO_PROXY:-}" ]]; then
echo "ENV no_proxy $OPENIMRNETES_NO_PROXY" >> "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile" echo "ENV no_proxy $OPENIMRNETES_NO_PROXY" >> "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile"
fi fi
} }
function openim::build::ensure_docker_in_path() { function openim::build::ensure_docker_in_path() {
if [[ -z "$(which docker)" ]]; then if [[ -z "$(which docker)" ]]; then
openim::log::error "Can't find 'docker' in PATH, please fix and retry." openim::log::error "Can't find 'docker' in PATH, please fix and retry."
openim::log::error "See https://docs.docker.com/installation/#installation for installation instructions." openim::log::error "See https://docs.docker.com/installation/#installation for installation instructions."
return 1 return 1
fi fi
} }
function openim::build::ensure_tar() { function openim::build::ensure_tar() {
if [[ -n "${TAR:-}" ]]; then if [[ -n "${TAR:-}" ]]; then
return return
fi fi
# Find gnu tar if it is available, bomb out if not. # Find gnu tar if it is available, bomb out if not.
TAR=tar TAR=tar
if which gtar &>/dev/null; then if which gtar &>/dev/null; then
TAR=gtar TAR=gtar
else else
if which gnutar &>/dev/null; then if which gnutar &>/dev/null; then
TAR=gnutar TAR=gnutar
fi
fi
if ! "${TAR}" --version | grep -q GNU; then
echo " !!! Cannot find GNU tar. Build on Linux or install GNU tar"
echo " on Mac OS X (brew install gnu-tar)."
return 1
fi fi
fi
if ! "${TAR}" --version | grep -q GNU; then
echo " !!! Cannot find GNU tar. Build on Linux or install GNU tar"
echo " on Mac OS X (brew install gnu-tar)."
return 1
fi
} }
function openim::build::has_docker() { function openim::build::has_docker() {
which docker &> /dev/null which docker &> /dev/null
} }
function openim::build::has_ip() { function openim::build::has_ip() {
which ip &> /dev/null && ip -Version | grep 'iproute2' &> /dev/null which ip &> /dev/null && ip -Version | grep 'iproute2' &> /dev/null
} }
# Detect if a specific image exists # Detect if a specific image exists
@@ -304,12 +304,12 @@ which ip &> /dev/null && ip -Version | grep 'iproute2' &> /dev/null
# $1 - image repo name # $1 - image repo name
# $2 - image tag # $2 - image tag
function openim::build::docker_image_exists() { function openim::build::docker_image_exists() {
[[ -n $1 && -n $2 ]] || { [[ -n $1 && -n $2 ]] || {
openim::log::error "Internal error. Image not specified in docker_image_exists." openim::log::error "Internal error. Image not specified in docker_image_exists."
exit 2 exit 2
} }
[[ $("${DOCKER[@]}" images -q "${1}:${2}") ]] [[ $("${DOCKER[@]}" images -q "${1}:${2}") ]]
} }
# Delete all images that match a tag prefix except for the "current" version # Delete all images that match a tag prefix except for the "current" version
@@ -318,21 +318,21 @@ function openim::build::docker_image_exists() {
# $2: The tag base. We consider any image that matches $2* # $2: The tag base. We consider any image that matches $2*
# $3: The current image not to delete if provided # $3: The current image not to delete if provided
function openim::build::docker_delete_old_images() { function openim::build::docker_delete_old_images() {
# In Docker 1.12, we can replace this with # In Docker 1.12, we can replace this with
# docker images "$1" --format "{{.Tag}}" # docker images "$1" --format "{{.Tag}}"
for tag in $("${DOCKER[@]}" images "${1}" | tail -n +2 | awk '{print $2}') ; do for tag in $("${DOCKER[@]}" images "${1}" | tail -n +2 | awk '{print $2}') ; do
if [[ "${tag}" != "${2}"* ]] ; then if [[ "${tag}" != "${2}"* ]] ; then
V=3 openim::log::status "Keeping image ${1}:${tag}" V=3 openim::log::status "Keeping image ${1}:${tag}"
continue continue
fi fi
if [[ -z "${3:-}" || "${tag}" != "${3}" ]] ; then if [[ -z "${3:-}" || "${tag}" != "${3}" ]] ; then
V=2 openim::log::status "Deleting image ${1}:${tag}" V=2 openim::log::status "Deleting image ${1}:${tag}"
"${DOCKER[@]}" rmi "${1}:${tag}" >/dev/null "${DOCKER[@]}" rmi "${1}:${tag}" >/dev/null
else else
V=3 openim::log::status "Keeping image ${1}:${tag}" V=3 openim::log::status "Keeping image ${1}:${tag}"
fi fi
done done
} }
# Stop and delete all containers that match a pattern # Stop and delete all containers that match a pattern
@@ -340,36 +340,36 @@ done
# $1: The base container prefix # $1: The base container prefix
# $2: The current container to keep, if provided # $2: The current container to keep, if provided
function openim::build::docker_delete_old_containers() { function openim::build::docker_delete_old_containers() {
# In Docker 1.12 we can replace this line with # In Docker 1.12 we can replace this line with
# docker ps -a --format="{{.Names}}" # docker ps -a --format="{{.Names}}"
for container in $("${DOCKER[@]}" ps -a | tail -n +2 | awk '{print $NF}') ; do for container in $("${DOCKER[@]}" ps -a | tail -n +2 | awk '{print $NF}') ; do
if [[ "${container}" != "${1}"* ]] ; then if [[ "${container}" != "${1}"* ]] ; then
V=3 openim::log::status "Keeping container ${container}" V=3 openim::log::status "Keeping container ${container}"
continue continue
fi fi
if [[ -z "${2:-}" || "${container}" != "${2}" ]] ; then if [[ -z "${2:-}" || "${container}" != "${2}" ]] ; then
V=2 openim::log::status "Deleting container ${container}" V=2 openim::log::status "Deleting container ${container}"
openim::build::destroy_container "${container}" openim::build::destroy_container "${container}"
else else
V=3 openim::log::status "Keeping container ${container}" V=3 openim::log::status "Keeping container ${container}"
fi fi
done done
} }
# Takes $1 and computes a short has for it. Useful for unique tag generation # Takes $1 and computes a short has for it. Useful for unique tag generation
function openim::build::short_hash() { function openim::build::short_hash() {
[[ $# -eq 1 ]] || { [[ $# -eq 1 ]] || {
openim::log::error "Internal error. No data based to short_hash." openim::log::error "Internal error. No data based to short_hash."
exit 2 exit 2
} }
local short_hash local short_hash
if which md5 >/dev/null 2>&1; then if which md5 >/dev/null 2>&1; then
short_hash=$(md5 -q -s "$1") short_hash=$(md5 -q -s "$1")
else else
short_hash=$(echo -n "$1" | md5sum) short_hash=$(echo -n "$1" | md5sum)
fi fi
echo "${short_hash:0:10}" echo "${short_hash:0:10}"
} }
# Pedantically kill, wait-on and remove a container. The -f -v options # Pedantically kill, wait-on and remove a container. The -f -v options
@@ -377,15 +377,15 @@ echo "${short_hash:0:10}"
# container, wait to ensure it's stopped, then try the remove. This is # container, wait to ensure it's stopped, then try the remove. This is
# a workaround for bug https://github.com/docker/docker/issues/3968. # a workaround for bug https://github.com/docker/docker/issues/3968.
function openim::build::destroy_container() { function openim::build::destroy_container() {
"${DOCKER[@]}" kill "$1" >/dev/null 2>&1 || true "${DOCKER[@]}" kill "$1" >/dev/null 2>&1 || true
if [[ $("${DOCKER[@]}" version --format '{{.Server.Version}}') = 17.06.0* ]]; then if [[ $("${DOCKER[@]}" version --format '{{.Server.Version}}') = 17.06.0* ]]; then
# Workaround https://github.com/moby/moby/issues/33948. # Workaround https://github.com/moby/moby/issues/33948.
# TODO: remove when 17.06.0 is not relevant anymore # TODO: remove when 17.06.0 is not relevant anymore
DOCKER_API_VERSION=v1.29 "${DOCKER[@]}" wait "$1" >/dev/null 2>&1 || true DOCKER_API_VERSION=v1.29 "${DOCKER[@]}" wait "$1" >/dev/null 2>&1 || true
else else
"${DOCKER[@]}" wait "$1" >/dev/null 2>&1 || true "${DOCKER[@]}" wait "$1" >/dev/null 2>&1 || true
fi fi
"${DOCKER[@]}" rm -f -v "$1" >/dev/null 2>&1 || true "${DOCKER[@]}" rm -f -v "$1" >/dev/null 2>&1 || true
} }
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -393,47 +393,47 @@ fi
function openim::build::clean() { function openim::build::clean() {
if openim::build::has_docker ; then if openim::build::has_docker ; then
openim::build::docker_delete_old_containers "${OPENIM_BUILD_CONTAINER_NAME_BASE}" openim::build::docker_delete_old_containers "${OPENIM_BUILD_CONTAINER_NAME_BASE}"
openim::build::docker_delete_old_containers "${OPENIM_RSYNC_CONTAINER_NAME_BASE}" openim::build::docker_delete_old_containers "${OPENIM_RSYNC_CONTAINER_NAME_BASE}"
openim::build::docker_delete_old_containers "${OPENIM_DATA_CONTAINER_NAME_BASE}" openim::build::docker_delete_old_containers "${OPENIM_DATA_CONTAINER_NAME_BASE}"
openim::build::docker_delete_old_images "${OPENIM_BUILD_IMAGE_REPO}" "${OPENIM_BUILD_IMAGE_TAG_BASE}" openim::build::docker_delete_old_images "${OPENIM_BUILD_IMAGE_REPO}" "${OPENIM_BUILD_IMAGE_TAG_BASE}"
V=2 openim::log::status "Cleaning all untagged docker images"
"${DOCKER[@]}" rmi "$("${DOCKER[@]}" images -q --filter 'dangling=true')" 2> /dev/null || true
fi
if [[ -d "${LOCAL_OUTPUT_ROOT}" ]]; then V=2 openim::log::status "Cleaning all untagged docker images"
openim::log::status "Removing _output directory" "${DOCKER[@]}" rmi "$("${DOCKER[@]}" images -q --filter 'dangling=true')" 2> /dev/null || true
rm -rf "${LOCAL_OUTPUT_ROOT}" fi
fi
if [[ -d "${LOCAL_OUTPUT_ROOT}" ]]; then
openim::log::status "Removing _output directory"
rm -rf "${LOCAL_OUTPUT_ROOT}"
fi
} }
# Set up the context directory for the openim-build image and build it. # Set up the context directory for the openim-build image and build it.
function openim::build::build_image() { function openim::build::build_image() {
mkdir -p "${LOCAL_OUTPUT_BUILD_CONTEXT}" mkdir -p "${LOCAL_OUTPUT_BUILD_CONTEXT}"
# Make sure the context directory owned by the right user for syncing sources to container. # Make sure the context directory owned by the right user for syncing sources to container.
chown -R "${USER_ID}":"${GROUP_ID}" "${LOCAL_OUTPUT_BUILD_CONTEXT}" chown -R "${USER_ID}":"${GROUP_ID}" "${LOCAL_OUTPUT_BUILD_CONTEXT}"
cp /etc/localtime "${LOCAL_OUTPUT_BUILD_CONTEXT}/" cp /etc/localtime "${LOCAL_OUTPUT_BUILD_CONTEXT}/"
cp "${OPENIM_ROOT}/build/build-image/Dockerfile" "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile" cp "${OPENIM_ROOT}/build/build-image/Dockerfile" "${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile"
cp "${OPENIM_ROOT}/build/build-image/rsyncd.sh" "${LOCAL_OUTPUT_BUILD_CONTEXT}/" cp "${OPENIM_ROOT}/build/build-image/rsyncd.sh" "${LOCAL_OUTPUT_BUILD_CONTEXT}/"
dd if=/dev/urandom bs=512 count=1 2>/dev/null | LC_ALL=C tr -dc 'A-Za-z0-9' | dd bs=32 count=1 2>/dev/null > "${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password" dd if=/dev/urandom bs=512 count=1 2>/dev/null | LC_ALL=C tr -dc 'A-Za-z0-9' | dd bs=32 count=1 2>/dev/null > "${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password"
chmod go= "${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password" chmod go= "${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password"
openim::build::update_dockerfile openim::build::update_dockerfile
openim::build::set_proxy openim::build::set_proxy
openim::build::docker_build "${OPENIM_BUILD_IMAGE}" "${LOCAL_OUTPUT_BUILD_CONTEXT}" 'false' openim::build::docker_build "${OPENIM_BUILD_IMAGE}" "${LOCAL_OUTPUT_BUILD_CONTEXT}" 'false'
# Clean up old versions of everything # Clean up old versions of everything
openim::build::docker_delete_old_containers "${OPENIM_BUILD_CONTAINER_NAME_BASE}" "${OPENIM_BUILD_CONTAINER_NAME}" openim::build::docker_delete_old_containers "${OPENIM_BUILD_CONTAINER_NAME_BASE}" "${OPENIM_BUILD_CONTAINER_NAME}"
openim::build::docker_delete_old_containers "${OPENIM_RSYNC_CONTAINER_NAME_BASE}" "${OPENIM_RSYNC_CONTAINER_NAME}" openim::build::docker_delete_old_containers "${OPENIM_RSYNC_CONTAINER_NAME_BASE}" "${OPENIM_RSYNC_CONTAINER_NAME}"
openim::build::docker_delete_old_containers "${OPENIM_DATA_CONTAINER_NAME_BASE}" "${OPENIM_DATA_CONTAINER_NAME}" openim::build::docker_delete_old_containers "${OPENIM_DATA_CONTAINER_NAME_BASE}" "${OPENIM_DATA_CONTAINER_NAME}"
openim::build::docker_delete_old_images "${OPENIM_BUILD_IMAGE_REPO}" "${OPENIM_BUILD_IMAGE_TAG_BASE}" "${OPENIM_BUILD_IMAGE_TAG}" openim::build::docker_delete_old_images "${OPENIM_BUILD_IMAGE_REPO}" "${OPENIM_BUILD_IMAGE_TAG_BASE}" "${OPENIM_BUILD_IMAGE_TAG}"
openim::build::ensure_data_container openim::build::ensure_data_container
openim::build::sync_to_container openim::build::sync_to_container
} }
# Build a docker image from a Dockerfile. # Build a docker image from a Dockerfile.
@@ -441,14 +441,14 @@ openim::build::sync_to_container
# $2 is the location of the "context" directory, with the Dockerfile at the root. # $2 is the location of the "context" directory, with the Dockerfile at the root.
# $3 is the value to set the --pull flag for docker build; true by default # $3 is the value to set the --pull flag for docker build; true by default
function openim::build::docker_build() { function openim::build::docker_build() {
local -r image=$1 local -r image=$1
local -r context_dir=$2 local -r context_dir=$2
local -r pull="${3:-true}" local -r pull="${3:-true}"
local -ra build_cmd=("${DOCKER[@]}" build -t "${image}" "--pull=${pull}" "${context_dir}") local -ra build_cmd=("${DOCKER[@]}" build -t "${image}" "--pull=${pull}" "${context_dir}")
openim::log::status "Building Docker image ${image}" openim::log::status "Building Docker image ${image}"
local docker_output local docker_output
docker_output=$("${build_cmd[@]}" 2>&1) || { docker_output=$("${build_cmd[@]}" 2>&1) || {
cat <<EOF >&2 cat <<EOF >&2
+++ Docker build command failed for ${image} +++ Docker build command failed for ${image}
@@ -459,61 +459,61 @@ To retry manually, run:
${build_cmd[*]} ${build_cmd[*]}
EOF EOF
return 1 return 1
} }
} }
function openim::build::ensure_data_container() { function openim::build::ensure_data_container() {
# If the data container exists AND exited successfully, we can use it. # If the data container exists AND exited successfully, we can use it.
# Otherwise nuke it and start over. # Otherwise nuke it and start over.
local ret=0 local ret=0
local code=0 local code=0
code=$(docker inspect \ code=$(docker inspect \
-f '{{.State.ExitCode}}' \ -f '{{.State.ExitCode}}' \
"${OPENIM_DATA_CONTAINER_NAME}" 2>/dev/null) || ret=$? "${OPENIM_DATA_CONTAINER_NAME}" 2>/dev/null) || ret=$?
if [[ "${ret}" == 0 && "${code}" != 0 ]]; then if [[ "${ret}" == 0 && "${code}" != 0 ]]; then
openim::build::destroy_container "${OPENIM_DATA_CONTAINER_NAME}" openim::build::destroy_container "${OPENIM_DATA_CONTAINER_NAME}"
ret=1 ret=1
fi fi
if [[ "${ret}" != 0 ]]; then if [[ "${ret}" != 0 ]]; then
openim::log::status "Creating data container ${OPENIM_DATA_CONTAINER_NAME}" openim::log::status "Creating data container ${OPENIM_DATA_CONTAINER_NAME}"
# We have to ensure the directory exists, or else the docker run will # We have to ensure the directory exists, or else the docker run will
# create it as root. # create it as root.
mkdir -p "${LOCAL_OUTPUT_GOPATH}" mkdir -p "${LOCAL_OUTPUT_GOPATH}"
# We want this to run as root to be able to chown, so non-root users can # We want this to run as root to be able to chown, so non-root users can
# later use the result as a data container. This run both creates the data # later use the result as a data container. This run both creates the data
# container and chowns the GOPATH. # container and chowns the GOPATH.
# #
# The data container creates volumes for all of the directories that store # The data container creates volumes for all of the directories that store
# intermediates for the Go build. This enables incremental builds across # intermediates for the Go build. This enables incremental builds across
# Docker sessions. The *_cgo paths are re-compiled versions of the go std # Docker sessions. The *_cgo paths are re-compiled versions of the go std
# libraries for true static building. # libraries for true static building.
local -ra docker_cmd=( local -ra docker_cmd=(
"${DOCKER[@]}" run "${DOCKER[@]}" run
--volume "${REMOTE_ROOT}" # white-out the whole output dir --volume "${REMOTE_ROOT}" # white-out the whole output dir
--volume /usr/local/go/pkg/linux_386_cgo --volume /usr/local/go/pkg/linux_386_cgo
--volume /usr/local/go/pkg/linux_amd64_cgo --volume /usr/local/go/pkg/linux_amd64_cgo
--volume /usr/local/go/pkg/linux_arm_cgo --volume /usr/local/go/pkg/linux_arm_cgo
--volume /usr/local/go/pkg/linux_arm64_cgo --volume /usr/local/go/pkg/linux_arm64_cgo
--volume /usr/local/go/pkg/linux_ppc64le_cgo --volume /usr/local/go/pkg/linux_ppc64le_cgo
--volume /usr/local/go/pkg/darwin_amd64_cgo --volume /usr/local/go/pkg/darwin_amd64_cgo
--volume /usr/local/go/pkg/darwin_386_cgo --volume /usr/local/go/pkg/darwin_386_cgo
--volume /usr/local/go/pkg/windows_amd64_cgo --volume /usr/local/go/pkg/windows_amd64_cgo
--volume /usr/local/go/pkg/windows_386_cgo --volume /usr/local/go/pkg/windows_386_cgo
--name "${OPENIM_DATA_CONTAINER_NAME}" --name "${OPENIM_DATA_CONTAINER_NAME}"
--hostname "${HOSTNAME}" --hostname "${HOSTNAME}"
"${OPENIM_BUILD_IMAGE}" "${OPENIM_BUILD_IMAGE}"
chown -R "${USER_ID}":"${GROUP_ID}" chown -R "${USER_ID}":"${GROUP_ID}"
"${REMOTE_ROOT}" "${REMOTE_ROOT}"
/usr/local/go/pkg/ /usr/local/go/pkg/
) )
"${docker_cmd[@]}" "${docker_cmd[@]}"
fi fi
} }
# Build all openim commands. # Build all openim commands.
function openim::build::build_command() { function openim::build::build_command() {
openim::log::status "Running build command..." openim::log::status "Running build command..."
make -C "${OPENIM_ROOT}" multiarch make -C "${OPENIM_ROOT}" multiarch
} }
+6 -6
View File
@@ -19,11 +19,11 @@
echo "mode: atomic" > coverage.txt echo "mode: atomic" > coverage.txt
for d in $(find ./* -maxdepth 10 -type d); do for d in $(find ./* -maxdepth 10 -type d); do
if ls $d/*.go &> /dev/null; then if ls $d/*.go &> /dev/null; then
go test -coverprofile=profile.out -covermode=atomic $d go test -coverprofile=profile.out -covermode=atomic $d
if [ -f profile.out ]; then if [ -f profile.out ]; then
cat profile.out | grep -v "mode: " >> /tmp/coverage.txt cat profile.out | grep -v "mode: " >> /tmp/coverage.txt
rm profile.out rm profile.out
fi
fi fi
fi
done done
+11 -11
View File
@@ -15,16 +15,16 @@
if ! command -v pv &> /dev/null if ! command -v pv &> /dev/null
then then
echo "pv not found, installing..." echo "pv not found, installing..."
if [ -e /etc/debian_version ]; then if [ -e /etc/debian_version ]; then
sudo apt-get update sudo apt-get update
sudo apt-get install -y pv sudo apt-get install -y pv
elif [ -e /etc/redhat-release ]; then elif [ -e /etc/redhat-release ]; then
sudo yum install -y pv sudo yum install -y pv
else else
echo "Unsupported OS, please install pv manually." echo "Unsupported OS, please install pv manually."
exit 1 exit 1
fi fi
fi fi
readonly t_reset=$(tput sgr0) readonly t_reset=$(tput sgr0)
@@ -42,8 +42,8 @@ openim::util::ensure-bash-version
trap 'openim::util::onCtrlC' INT trap 'openim::util::onCtrlC' INT
function openim::util::onCtrlC() { function openim::util::onCtrlC() {
echo -e "\n${t_reset}Ctrl+C Press it. It's exiting openim make init..." echo -e "\n${t_reset}Ctrl+C Press it. It's exiting openim make init..."
exit 0 exit 0
} }
openim::util::desc "========> Welcome to the OpenIM Demo" openim::util::desc "========> Welcome to the OpenIM Demo"
+48 -48
View File
@@ -22,61 +22,61 @@ cd "$OPENIM_ROOT"
openim::util::check_docker_and_compose_versions openim::util::check_docker_and_compose_versions
progress() { progress() {
local _main_pid="$1" local _main_pid="$1"
local _length=20 local _length=20
local _ratio=1 local _ratio=1
local _colors=("31" "32" "33" "34" "35" "36" "37") local _colors=("31" "32" "33" "34" "35" "36" "37")
local _wave=("▁" "▂" "▃" "▄" "▅" "▆" "▇" "█" "▇" "▆" "▅" "▄" "▃" "▂") local _wave=("▁" "▂" "▃" "▄" "▅" "▆" "▇" "█" "▇" "▆" "▅" "▄" "▃" "▂")
while pgrep -P "$_main_pid" &> /dev/null; do while pgrep -P "$_main_pid" &> /dev/null; do
local _mark='>' local _mark='>'
local _progress_bar= local _progress_bar=
for ((i = 1; i <= _length; i++)); do for ((i = 1; i <= _length; i++)); do
if ((i > _ratio)); then if ((i > _ratio)); then
_mark='-' _mark='-'
fi fi
_progress_bar="${_progress_bar}${_mark}" _progress_bar="${_progress_bar}${_mark}"
done
local _color_idx=$((_ratio % ${#_colors[@]}))
local _color_prefix="\033[${_colors[_color_idx]}m"
local _reset_suffix="\033[0m"
local _wave_idx=$((_ratio % ${#_wave[@]}))
local _wave_progress=${_wave[_wave_idx]}
printf "Progress: ${_color_prefix}${_progress_bar}${_reset_suffix} ${_wave_progress} Countdown: %2ds \r" "$_countdown"
((_ratio++))
((_ratio > _length)) && _ratio=1
sleep 0.1
done done
local _color_idx=$((_ratio % ${#_colors[@]}))
local _color_prefix="\033[${_colors[_color_idx]}m"
local _reset_suffix="\033[0m"
local _wave_idx=$((_ratio % ${#_wave[@]}))
local _wave_progress=${_wave[_wave_idx]}
printf "Progress: ${_color_prefix}${_progress_bar}${_reset_suffix} ${_wave_progress} Countdown: %2ds \r" "$_countdown"
((_ratio++))
((_ratio > _length)) && _ratio=1
sleep 0.1
done
} }
countdown() { countdown() {
local _duration="$1" local _duration="$1"
for ((i = _duration; i >= 1; i--)); do for ((i = _duration; i >= 1; i--)); do
printf "\rCountdown: %2ds \r" "$i" printf "\rCountdown: %2ds \r" "$i"
sleep 1 sleep 1
done done
printf "\rCountdown: %2ds \r" "$_duration" printf "\rCountdown: %2ds \r" "$_duration"
} }
do_sth() { do_sth() {
echo "++++++++++++++++++++++++" echo "++++++++++++++++++++++++"
progress $$ & progress $$ &
local _progress_pid=$! local _progress_pid=$!
local _countdown=30 local _countdown=30
countdown "$_countdown" & countdown "$_countdown" &
local _countdown_pid=$! local _countdown_pid=$!
sleep 30 sleep 30
kill "$_progress_pid" "$_countdown_pid" kill "$_progress_pid" "$_countdown_pid"
"${SCRIPTS_ROOT}/check-all.sh" "${SCRIPTS_ROOT}/check-all.sh"
echo -e "${PURPLE_PREFIX}=========> Check docker-compose status ${COLOR_SUFFIX} \n" echo -e "${PURPLE_PREFIX}=========> Check docker-compose status ${COLOR_SUFFIX} \n"
} }
set -e set -e
+2 -2
View File
@@ -18,9 +18,9 @@ OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
version="${VERSION}" version="${VERSION}"
if [ "${version}" == "" ];then if [ "${version}" == "" ];then
version=v$(${OPENIM_ROOT}/_output/tools/gsemver bump) version=v`${OPENIM_ROOT}/_output/tools/gsemver bump`
fi fi
if [ -z "$(git tag -l ${version})" ];then if [ -z "`git tag -l ${version}`" ];then
git tag -a -m "release version ${version}" ${version} git tag -a -m "release version ${version}" ${version}
fi fi
+2 -2
View File
@@ -67,7 +67,7 @@ echo -e "=== any\nRepresents an untyped JSON map - see the description of the fi
asciidoctor definitions.adoc asciidoctor definitions.adoc
asciidoctor paths.adoc asciidoctor paths.adoc
cp "$OPENIM_OUTPUT_TMP/definitions.html" "$OPENIM_OUTPUT_TMP/_output/" cp ${OPENIM_OUTPUT_TMP}/definitions.html ${OPENIM_OUTPUT_TMP}/_output/
cp "$OPENIM_OUTPUT_TMP/paths.html" "$OPENIM_OUTPUT_TMP/_output/operations.html" cp ${OPENIM_OUTPUT_TMP}/paths.html ${OPENIM_OUTPUT_TMP}/_output/operations.html
success "SUCCESS" success "SUCCESS"
+9 -9
View File
@@ -25,12 +25,12 @@ OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
source "${OPENIM_ROOT}/scripts/lib/init.sh" source "${OPENIM_ROOT}/scripts/lib/init.sh"
if [ $# -ne 2 ];then if [ $# -ne 2 ];then
openim::log::error "Usage: scripts/genconfig.sh scripts/environment.sh configs/config.yaml" openim::log::error "Usage: scripts/genconfig.sh scripts/environment.sh configs/config.yaml"
exit 1 exit 1
fi fi
if [ -z "${OPENIM_IP}" ]; then if [ -z "${OPENIM_IP}" ]; then
openim::util::require-dig openim::util::require-dig
fi fi
source "${env_file}" source "${env_file}"
@@ -40,15 +40,15 @@ declare -A envs
set +u set +u
for env in $(sed -n 's/^[^#].*${\(.*\)}.*/\1/p' ${template_file}) for env in $(sed -n 's/^[^#].*${\(.*\)}.*/\1/p' ${template_file})
do do
if [ -z "$(eval echo \$${env})" ];then if [ -z "$(eval echo \$${env})" ];then
openim::log::error "environment variable '${env}' not set" openim::log::error "environment variable '${env}' not set"
missing=true missing=true
fi fi
done done
if [ "${missing}" ];then if [ "${missing}" ];then
openim::log::error "You may run 'source scripts/environment.sh' to set these environment" openim::log::error 'You may run `source scripts/environment.sh` to set these environment'
exit 1 exit 1
fi fi
eval "cat << EOF eval "cat << EOF
+27 -27
View File
@@ -14,43 +14,43 @@
# limitations under the License. # limitations under the License.
DEFAULT_DIRS=( DEFAULT_DIRS=(
"pkg" "pkg"
"internal/pkg" "internal/pkg"
) )
BASE_URL="github.com/openimsdk/open-im-server" BASE_URL="github.com/openimsdk/open-im-server"
usage() { usage() {
echo "Usage: $0 [OPTIONS]" echo "Usage: $0 [OPTIONS]"
echo echo
echo "This script iterates over directories and generates doc.go if necessary." echo "This script iterates over directories and generates doc.go if necessary."
echo "By default, it processes 'pkg' and 'internal/pkg' directories." echo "By default, it processes 'pkg' and 'internal/pkg' directories."
echo echo
echo "Options:" echo "Options:"
echo " -d DIRS, --dirs DIRS Specify the directories to be processed, separated by commas. E.g., 'pkg,internal/pkg'." echo " -d DIRS, --dirs DIRS Specify the directories to be processed, separated by commas. E.g., 'pkg,internal/pkg'."
echo " -u URL, --url URL Set the base URL for the import path. Default is '$BASE_URL'." echo " -u URL, --url URL Set the base URL for the import path. Default is '$BASE_URL'."
echo " -h, --help Show this help message." echo " -h, --help Show this help message."
echo echo
} }
process_dir() { process_dir() {
local dir=$1 local dir=$1
local base_url=$2 local base_url=$2
for d in $(find $dir -type d); do for d in $(find $dir -type d); do
if [ ! -f $d/doc.go ]; then if [ ! -f $d/doc.go ]; then
if ls $d/*.go > /dev/null 2>&1; then if ls $d/*.go > /dev/null 2>&1; then
echo $d/doc.go echo $d/doc.go
echo "package $(basename $d) // import \"$base_url/$d\"" > $d/doc.go echo "package $(basename $d) // import \"$base_url/$d\"" > $d/doc.go
fi fi
fi fi
done done
} }
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
key="$1" key="$1"
case $key in case $key in
-d|--dirs) -d|--dirs)
IFS=',' read -ra DIRS <<< "$2" IFS=',' read -ra DIRS <<< "$2"
shift # shift past argument shift # shift past argument
shift # shift past value shift # shift past value
+19 -19
View File
@@ -34,15 +34,15 @@ RED="\e[31m"
ENDCOLOR="\e[0m" ENDCOLOR="\e[0m"
printMessage() { printMessage() {
printf "${YELLOW}OpenIM : $1${ENDCOLOR}\n" printf "${YELLOW}OpenIM : $1${ENDCOLOR}\n"
} }
printSuccess() { printSuccess() {
printf "${GREEN}OpenIM : $1${ENDCOLOR}\n" printf "${GREEN}OpenIM : $1${ENDCOLOR}\n"
} }
printError() { printError() {
printf "${RED}OpenIM : $1${ENDCOLOR}\n" printf "${RED}OpenIM : $1${ENDCOLOR}\n"
} }
printMessage "Running the OpenIM commit-msg hook." printMessage "Running the OpenIM commit-msg hook."
@@ -50,9 +50,9 @@ printMessage "Running the OpenIM commit-msg hook."
# This example catches duplicate Signed-off-by lines. # This example catches duplicate Signed-off-by lines.
test "" = "$(grep '^Signed-off-by: ' "$1" | test "" = "$(grep '^Signed-off-by: ' "$1" |
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
echo >&2 Duplicate Signed-off-by lines. echo >&2 Duplicate Signed-off-by lines.
exit 1 exit 1
} }
# TODO: go-gitlint dir set # TODO: go-gitlint dir set
@@ -60,21 +60,21 @@ OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/../..
GITLINT_DIR="$OPENIM_ROOT/_output/tools/go-gitlint" GITLINT_DIR="$OPENIM_ROOT/_output/tools/go-gitlint"
$GITLINT_DIR \ $GITLINT_DIR \
--msg-file=$1 \ --msg-file=$1 \
--subject-regex="^(build|chore|ci|docs|feat|feature|fix|perf|refactor|revert|style|bot|test)(.*)?:\s?.*" \ --subject-regex="^(build|chore|ci|docs|feat|feature|fix|perf|refactor|revert|style|bot|test)(.*)?:\s?.*" \
--subject-maxlen=150 \ --subject-maxlen=150 \
--subject-minlen=10 \ --subject-minlen=10 \
--body-regex=".*" \ --body-regex=".*" \
--max-parents=1 --max-parents=1
if [ $? -ne 0 ] if [ $? -ne 0 ]
then then
if ! command -v $GITLINT_DIR &>/dev/null; then if ! command -v $GITLINT_DIR &>/dev/null; then
printError "$GITLINT_DIR not found. Please run 'make tools' OR 'make tools.verify.go-gitlint' make verto install it." printError "$GITLINT_DIR not found. Please run 'make tools' OR 'make tools.verify.go-gitlint' make verto install it."
fi fi
printError "Please fix your commit message to match kubecub coding standards" printError "Please fix your commit message to match kubecub coding standards"
printError "https://gist.github.com/cubxxw/126b72104ac0b0ca484c9db09c3e5694#file-githook-md" printError "https://gist.github.com/cubxxw/126b72104ac0b0ca484c9db09c3e5694#file-githook-md"
exit 1 exit 1
fi fi
### Add Sign-off-by line to the end of the commit message ### Add Sign-off-by line to the end of the commit message
@@ -88,5 +88,5 @@ SIGNED_OFF_BY_EXISTS=$?
# Add "Signed-off-by" line if it doesn't exist # Add "Signed-off-by" line if it doesn't exist
if [ $SIGNED_OFF_BY_EXISTS -ne 0 ]; then if [ $SIGNED_OFF_BY_EXISTS -ne 0 ]; then
echo -e "\nSigned-off-by: $NAME <$EMAIL>" >> "$1" echo -e "\nSigned-off-by: $NAME <$EMAIL>" >> "$1"
fi fi
+11 -11
View File
@@ -34,15 +34,15 @@ RED="\e[31m"
ENDCOLOR="\e[0m" ENDCOLOR="\e[0m"
printMessage() { printMessage() {
printf "${YELLOW}openim : $1${ENDCOLOR}\n" printf "${YELLOW}openim : $1${ENDCOLOR}\n"
} }
printSuccess() { printSuccess() {
printf "${GREEN}openim : $1${ENDCOLOR}\n" printf "${GREEN}openim : $1${ENDCOLOR}\n"
} }
printError() { printError() {
printf "${RED}openim : $1${ENDCOLOR}\n" printf "${RED}openim : $1${ENDCOLOR}\n"
} }
printMessage "Running local openim pre-commit hook." printMessage "Running local openim pre-commit hook."
@@ -55,9 +55,9 @@ limit=${GIT_FILE_SIZE_LIMIT:-2000000} # Default 2MB
limitInMB=$(( $limit / 1000000 )) limitInMB=$(( $limit / 1000000 ))
function file_too_large(){ function file_too_large(){
filename=$0 filename=$0
filesize=$(( $1 / 2**20 )) filesize=$(( $1 / 2**20 ))
cat <<HEREDOC cat <<HEREDOC
File $filename is $filesize MB, which is larger than github's maximum File $filename is $filesize MB, which is larger than github's maximum
@@ -65,8 +65,8 @@ function file_too_large(){
Commit aborted Commit aborted
HEREDOC HEREDOC
git status git status
} }
# Move to the repo root so git files paths make sense # Move to the repo root so git files paths make sense
@@ -77,9 +77,9 @@ empty_tree=$( git hash-object -t tree /dev/null )
if git rev-parse --verify HEAD > /dev/null 2>&1 if git rev-parse --verify HEAD > /dev/null 2>&1
then then
against=HEAD against=HEAD
else else
against="$empty_tree" against="$empty_tree"
fi fi
# Set split so that for loop below can handle spaces in file names by splitting on line breaks # Set split so that for loop below can handle spaces in file names by splitting on line breaks
@@ -104,7 +104,7 @@ fi
if [[ ! $local_branch =~ $valid_branch_regex ]] if [[ ! $local_branch =~ $valid_branch_regex ]]
then then
printError "There is something wrong with your branch name. Branch names in this project must adhere to this contract: $valid_branch_regex. printError "There is something wrong with your branch name. Branch names in this project must adhere to this contract: $valid_branch_regex.
Your commit will be rejected. You should rename your branch to a valid name(feat/name OR bug/name) and try again." Your commit will be rejected. You should rename your branch to a valid name(feat/name OR bug/name) and try again."
printError "For more on this, read on: https://gist.github.com/cubxxw/126b72104ac0b0ca484c9db09c3e5694" printError "For more on this, read on: https://gist.github.com/cubxxw/126b72104ac0b0ca484c9db09c3e5694"
exit 1 exit 1
+5 -5
View File
@@ -25,20 +25,20 @@ local_branch="$(git rev-parse --abbrev-ref HEAD)"
valid_branch_regex="^(main|master|develop|release(-[a-zA-Z0-9._-]+)?)$|(feature|feat|openim|hotfix|test|bug|ci|cicd|style|)\/[a-z0-9._-]+$|^HEAD$" valid_branch_regex="^(main|master|develop|release(-[a-zA-Z0-9._-]+)?)$|(feature|feat|openim|hotfix|test|bug|ci|cicd|style|)\/[a-z0-9._-]+$|^HEAD$"
printMessage() { printMessage() {
printf "${YELLOW}OpenIM : $1${ENDCOLOR}\n" printf "${YELLOW}OpenIM : $1${ENDCOLOR}\n"
} }
printSuccess() { printSuccess() {
printf "${GREEN}OpenIM : $1${ENDCOLOR}\n" printf "${GREEN}OpenIM : $1${ENDCOLOR}\n"
} }
printError() { printError() {
printf "${RED}OpenIM : $1${ENDCOLOR}\n" printf "${RED}OpenIM : $1${ENDCOLOR}\n"
} }
printMessage "Running local OpenIM pre-push hook." printMessage "Running local OpenIM pre-push hook."
if [[ $(git status --porcelain) ]]; then if [[ `git status --porcelain` ]]; then
printError "This scripts needs to run against committed code only. Please commit or stash you changes." printError "This scripts needs to run against committed code only. Please commit or stash you changes."
exit 1 exit 1
fi fi
@@ -101,7 +101,7 @@ print_color "Deleted Files: ${deleted_files}" "${BACKGROUND_GREEN}"
if [[ ! $local_branch =~ $valid_branch_regex ]] if [[ ! $local_branch =~ $valid_branch_regex ]]
then then
printError "There is something wrong with your branch name. Branch names in this project must adhere to this contract: $valid_branch_regex. printError "There is something wrong with your branch name. Branch names in this project must adhere to this contract: $valid_branch_regex.
Your commit will be rejected. You should rename your branch to a valid name(feat/name OR fix/name) and try again." Your commit will be rejected. You should rename your branch to a valid name(feat/name OR fix/name) and try again."
printError "For more on this, read on: https://gist.github.com/cubxxw/126b72104ac0b0ca484c9db09c3e5694" printError "For more on this, read on: https://gist.github.com/cubxxw/126b72104ac0b0ca484c9db09c3e5694"
exit 1 exit 1
+23 -25
View File
@@ -31,7 +31,7 @@ readonly ENV_FILE=${ENV_FILE:-"${OPENIM_ROOT}/scripts/install/environment.sh"}
# Templates for configuration files # Templates for configuration files
declare -A TEMPLATES=( declare -A TEMPLATES=(
["${OPENIM_ROOT}/deployments/templates/env-template.yaml"]="${OPENIM_ROOT}/.env" ["${OPENIM_ROOT}/deployments/templates/env-template.yaml"]="${OPENIM_ROOT}/.env"
["${OPENIM_ROOT}/deployments/templates/config.yaml"]="${OPENIM_ROOT}/config/config.yaml" ["${OPENIM_ROOT}/deployments/templates/config.yaml"]="${OPENIM_ROOT}/config/openim.yaml"
["${OPENIM_ROOT}/deployments/templates/prometheus.yml"]="${OPENIM_ROOT}/config/prometheus.yml" ["${OPENIM_ROOT}/deployments/templates/prometheus.yml"]="${OPENIM_ROOT}/config/prometheus.yml"
["${OPENIM_ROOT}/deployments/templates/alertmanager.yml"]="${OPENIM_ROOT}/config/alertmanager.yml" ["${OPENIM_ROOT}/deployments/templates/alertmanager.yml"]="${OPENIM_ROOT}/config/alertmanager.yml"
) )
@@ -39,7 +39,7 @@ declare -A TEMPLATES=(
# Templates for example files # Templates for example files
declare -A EXAMPLES=( declare -A EXAMPLES=(
["${OPENIM_ROOT}/deployments/templates/env-template.yaml"]="${OPENIM_ROOT}/config/templates/env.template" ["${OPENIM_ROOT}/deployments/templates/env-template.yaml"]="${OPENIM_ROOT}/config/templates/env.template"
["${OPENIM_ROOT}/deployments/templates/config.yaml"]="${OPENIM_ROOT}/config/templates/config.yaml.template" ["${OPENIM_ROOT}/deployments/templates/config.yaml"]="${OPENIM_ROOT}/config/templates/openim.yaml.template"
["${OPENIM_ROOT}/deployments/templates/prometheus.yml"]="${OPENIM_ROOT}/config/templates/prometheus.yml.template" ["${OPENIM_ROOT}/deployments/templates/prometheus.yml"]="${OPENIM_ROOT}/config/templates/prometheus.yml.template"
["${OPENIM_ROOT}/deployments/templates/alertmanager.yml"]="${OPENIM_ROOT}/config/templates/alertmanager.yml.template" ["${OPENIM_ROOT}/deployments/templates/alertmanager.yml"]="${OPENIM_ROOT}/config/templates/alertmanager.yml.template"
) )
@@ -84,7 +84,7 @@ generate_config_files() {
local output_file="${TEMPLATES[$template]}" local output_file="${TEMPLATES[$template]}"
process_file "$template" "$output_file" true process_file "$template" "$output_file" true
done done
# Handle COPY_TEMPLATES array # Handle COPY_TEMPLATES array
for template in "${!COPY_TEMPLATES[@]}"; do for template in "${!COPY_TEMPLATES[@]}"; do
local output_file="${COPY_TEMPLATES[$template]}" local output_file="${COPY_TEMPLATES[$template]}"
@@ -95,25 +95,22 @@ generate_config_files() {
# Function to generate example files # Function to generate example files
generate_example_files() { generate_example_files() {
env_cmd="env -i" env_cmd="env -i"
env_vars["OPENIM_IP"]="127.0.0.1"
env_vars["LOG_STORAGE_LOCATION"]="../../"
for var in "${!env_vars[@]}"; do for var in "${!env_vars[@]}"; do
env_cmd+=" $var='${env_vars[$var]}'" env_cmd+=" $var='${env_vars[$var]}'"
done done
# Processing EXAMPLES array # Processing EXAMPLES array
for template in "${!EXAMPLES[@]}"; do for template in "${!EXAMPLES[@]}"; do
local example_file="${EXAMPLES[$template]}" local example_file="${EXAMPLES[$template]}"
process_file "$template" "$example_file" true process_file "$template" "$example_file" true
done done
# Processing COPY_EXAMPLES array # Processing COPY_EXAMPLES array
for template in "${!COPY_EXAMPLES[@]}"; do for template in "${!COPY_EXAMPLES[@]}"; do
local example_file="${COPY_EXAMPLES[$template]}" local example_file="${COPY_EXAMPLES[$template]}"
process_file "$template" "$example_file" false process_file "$template" "$example_file" false
done done
} }
# Function to process a single file, either by generating or copying # Function to process a single file, either by generating or copying
@@ -121,11 +118,11 @@ process_file() {
local template=$1 local template=$1
local output_file=$2 local output_file=$2
local use_genconfig=$3 local use_genconfig=$3
if [[ -f "${output_file}" ]]; then if [[ -f "${output_file}" ]]; then
if [[ "${FORCE_OVERWRITE}" == true ]]; then if [[ "${FORCE_OVERWRITE}" == true ]]; then
openim::log::info "Force overwriting ${output_file}." openim::log::info "Force overwriting ${output_file}."
elif [[ "${SKIP_EXISTING}" == true ]]; then elif [[ "${SKIP_EXISTING}" == true ]]; then
openim::log::info "Skipping generation of ${output_file} as it already exists." openim::log::info "Skipping generation of ${output_file} as it already exists."
return return
else else
@@ -142,7 +139,7 @@ process_file() {
openim::log::info "Generating ${output_file} as it does not exist." openim::log::info "Generating ${output_file} as it does not exist."
fi fi
fi fi
if [[ "$use_genconfig" == true ]]; then if [[ "$use_genconfig" == true ]]; then
openim::log::info "⌚ Working with template file: ${template} to generate ${output_file}..." openim::log::info "⌚ Working with template file: ${template} to generate ${output_file}..."
if [[ ! -f "${OPENIM_ROOT}/scripts/genconfig.sh" ]]; then if [[ ! -f "${OPENIM_ROOT}/scripts/genconfig.sh" ]]; then
@@ -150,15 +147,15 @@ process_file() {
exit 1 exit 1
fi fi
if [[ -n "${env_cmd}" ]]; then if [[ -n "${env_cmd}" ]]; then
eval "$env_cmd ${OPENIM_ROOT}/scripts/genconfig.sh '${ENV_FILE}' '${template}' > '${output_file}'" || { eval "$env_cmd ${OPENIM_ROOT}/scripts/genconfig.sh '${ENV_FILE}' '${template}' > '${output_file}'" || {
openim::log::error "Error processing template file ${template}" openim::log::error "Error processing template file ${template}"
exit 1 exit 1
} }
else else
"${OPENIM_ROOT}/scripts/genconfig.sh" "${ENV_FILE}" "${template}" > "${output_file}" || { "${OPENIM_ROOT}/scripts/genconfig.sh" "${ENV_FILE}" "${template}" > "${output_file}" || {
openim::log::error "Error processing template file ${template}" openim::log::error "Error processing template file ${template}"
exit 1 exit 1
} }
fi fi
else else
openim::log::info "📋 Copying ${template} to ${output_file}..." openim::log::info "📋 Copying ${template} to ${output_file}..."
@@ -167,7 +164,7 @@ process_file() {
exit 1 exit 1
} }
fi fi
sleep 0.5 sleep 0.5
} }
@@ -184,6 +181,7 @@ clean_config_files() {
# Function to clean example files # Function to clean example files
clean_example_files() { clean_example_files() {
# 合并 EXAMPLES 和 COPY_EXAMPLES 数组
local all_examples=("${EXAMPLES[@]}" "${COPY_EXAMPLES[@]}") local all_examples=("${EXAMPLES[@]}" "${COPY_EXAMPLES[@]}")
for example_file in "${all_examples[@]}"; do for example_file in "${all_examples[@]}"; do
@@ -199,32 +197,32 @@ while [[ $# -gt 0 ]]; do
-h|--help) -h|--help)
show_help show_help
exit 0 exit 0
;; ;;
--force) --force)
FORCE_OVERWRITE=true FORCE_OVERWRITE=true
shift shift
;; ;;
--skip) --skip)
SKIP_EXISTING=true SKIP_EXISTING=true
shift shift
;; ;;
--examples) --examples)
GENERATE_EXAMPLES=true GENERATE_EXAMPLES=true
shift shift
;; ;;
--clean-config) --clean-config)
CLEAN_CONFIG=true CLEAN_CONFIG=true
shift shift
;; ;;
--clean-examples) --clean-examples)
CLEAN_EXAMPLES=true CLEAN_EXAMPLES=true
shift shift
;; ;;
*) *)
echo "Unknown option: $1" echo "Unknown option: $1"
show_help show_help
exit 1 exit 1
;; ;;
esac esac
done done
+5 -5
View File
@@ -25,9 +25,9 @@ source "${OPENIM_ROOT}/scripts/install/common.sh"
openim::log::info "\n# Begin Install OpenIM Config" openim::log::info "\n# Begin Install OpenIM Config"
for file in "${OPENIM_SERVER_TARGETS[@]}"; do for file in "${OPENIM_SERVER_TARGETS[@]}"; do
VARNAME="$(echo $file | tr '[:lower:]' '[:upper:]' | tr '.' '_' | tr '-' '_')" VARNAME="$(echo $file | tr '[:lower:]' '[:upper:]' | tr '.' '_' | tr '-' '_')"
VARVALUE="$OPENIM_OUTPUT_HOSTBIN/$file" VARVALUE="$OPENIM_OUTPUT_HOSTBIN/$file"
# /etc/profile.d/openim-env.sh # /etc/profile.d/openim-env.sh
echo "export $VARNAME=$VARVALUE" > /etc/profile.d/openim-env.sh echo "export $VARNAME=$VARVALUE" > /etc/profile.d/openim-env.sh
source /etc/profile.d/openim-env.sh source /etc/profile.d/openim-env.sh
done done
+48 -48
View File
@@ -39,62 +39,62 @@ OPENIM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
HOOKS_DIR="${OPENIM_ROOT}/.git/hooks" HOOKS_DIR="${OPENIM_ROOT}/.git/hooks"
help_info() { help_info() {
echo "Usage: $0 [options]" echo "Usage: $0 [options]"
echo echo
echo "This script helps to manage git hooks." echo "This script helps to manage git hooks."
echo echo
echo "Options:" echo "Options:"
echo " -h, --help Show this help message and exit." echo " -h, --help Show this help message and exit."
echo " -d, --delete Delete the hooks that have been added." echo " -d, --delete Delete the hooks that have been added."
echo " By default, it will prompt to enable git hooks." echo " By default, it will prompt to enable git hooks."
} }
delete_hooks() { delete_hooks() {
for file in "${OPENIM_ROOT}"/scripts/githooks/*.sh; do for file in ${OPENIM_ROOT}/scripts/githooks/*.sh; do
hook_name=$(basename "$file" .sh) # This removes the .sh extension hook_name=$(basename "$file" .sh) # This removes the .sh extension
rm -f "$HOOKS_DIR/$hook_name" rm -f "$HOOKS_DIR/$hook_name"
done done
echo "Git hooks have been deleted." echo "Git hooks have been deleted."
} }
enable_hooks() { enable_hooks() {
echo "Would you like to:" echo "Would you like to:"
echo "1) Enable git hooks mode" echo "1) Enable git hooks mode"
echo "2) Delete existing git hooks" echo "2) Delete existing git hooks"
echo "Please select a number (or any other key to exit):" echo "Please select a number (or any other key to exit):"
read -r choice read -r choice
case "$choice" in case "$choice" in
1) 1)
for file in ${OPENIM_ROOT}/scripts/githooks/*.sh; do for file in ${OPENIM_ROOT}/scripts/githooks/*.sh; do
hook_name=$(basename "$file" .sh) # This removes the .sh extension hook_name=$(basename "$file" .sh) # This removes the .sh extension
cp -f "$file" "$HOOKS_DIR/$hook_name" cp -f "$file" "$HOOKS_DIR/$hook_name"
done done
chmod +x $HOOKS_DIR/* chmod +x $HOOKS_DIR/*
echo "Git hooks mode has been enabled." echo "Git hooks mode has been enabled."
echo "With git hooks enabled, every time you perform a git action (e.g. git commit), the corresponding hooks script will be triggered automatically." echo "With git hooks enabled, every time you perform a git action (e.g. git commit), the corresponding hooks script will be triggered automatically."
echo "This means that if the size of the file you're committing exceeds the set limit (e.g. 42MB), the commit will be rejected." echo "This means that if the size of the file you're committing exceeds the set limit (e.g. 42MB), the commit will be rejected."
;; ;;
2) 2)
delete_hooks delete_hooks
;; ;;
*) *)
echo "Exiting without making changes." echo "Exiting without making changes."
;; ;;
esac esac
} }
case "$1" in case "$1" in
-h|--help) -h|--help)
help_info help_info
;; ;;
-d|--delete) -d|--delete)
delete_hooks delete_hooks
;; ;;
*) *)
enable_hooks enable_hooks
;; ;;
esac esac
+12 -13
View File
@@ -49,10 +49,10 @@ DOCKER_COMPOSE_COMMAND=
# Check if docker-compose command is available # Check if docker-compose command is available
openim::util::check_docker_and_compose_versions openim::util::check_docker_and_compose_versions
if command -v docker compose &> /dev/null; then if command -v docker compose &> /dev/null; then
openim::log::info "docker compose command is available" openim::log::info "docker compose command is available"
DOCKER_COMPOSE_COMMAND="docker compose" DOCKER_COMPOSE_COMMAND="docker compose"
else else
DOCKER_COMPOSE_COMMAND="docker-compose" DOCKER_COMPOSE_COMMAND="docker-compose"
fi fi
export SERVER_IMAGE_VERSION export SERVER_IMAGE_VERSION
@@ -67,20 +67,19 @@ ${DOCKER_COMPOSE_COMMAND} up -d
# Function to check container status # Function to check container status
check_containers() { check_containers() {
if ! ${DOCKER_COMPOSE_COMMAND} ps | grep -q 'Up'; then if ! ${DOCKER_COMPOSE_COMMAND} ps | grep -q 'Up'; then
echo "Error: One or more docker containers failed to start." echo "Error: One or more docker containers failed to start."
${DOCKER_COMPOSE_COMMAND} logs openim-server ${DOCKER_COMPOSE_COMMAND} logs
${DOCKER_COMPOSE_COMMAND} logs openim-chat return 1
return 1 fi
fi return 0
return 0
} }
# Wait for a short period to allow containers to initialize # Wait for a short period to allow containers to initialize
sleep 30 sleep 30
${DOCKER_COMPOSE_COMMAND} ps
check_containers check_containers
${DOCKER_COMPOSE_COMMAND} logs openim-server
${DOCKER_COMPOSE_COMMAND} ps
popd popd
+51 -51
View File
@@ -24,66 +24,66 @@ OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
# Start MongoDB service # Start MongoDB service
docker run -d \ docker run -d \
--name mongo \ --name mongo \
-p 37017:27017 \ -p 37017:27017 \
-v "${DATA_DIR}/components/mongodb/data/db:/data/db" \ -v "${DATA_DIR}/components/mongodb/data/db:/data/db" \
-v "${DATA_DIR}/components/mongodb/data/logs:/data/logs" \ -v "${DATA_DIR}/components/mongodb/data/logs:/data/logs" \
-v "${DATA_DIR}/components/mongodb/data/conf:/etc/mongo" \ -v "${DATA_DIR}/components/mongodb/data/conf:/etc/mongo" \
-v "./scripts/mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro" \ -v "./scripts/mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro" \
-e TZ=Asia/Shanghai \ -e TZ=Asia/Shanghai \
-e wiredTigerCacheSizeGB=1 \ -e wiredTigerCacheSizeGB=1 \
-e MONGO_INITDB_ROOT_USERNAME=${OPENIM_USER} \ -e MONGO_INITDB_ROOT_USERNAME=${OPENIM_USER} \
-e MONGO_INITDB_ROOT_PASSWORD=${PASSWORD} \ -e MONGO_INITDB_ROOT_PASSWORD=${PASSWORD} \
-e MONGO_INITDB_DATABASE=openim_v3 \ -e MONGO_INITDB_DATABASE=openim_v3 \
-e MONGO_OPENIM_USERNAME=${OPENIM_USER} \ -e MONGO_OPENIM_USERNAME=${OPENIM_USER} \
-e MONGO_OPENIM_PASSWORD=${PASSWORD} \ -e MONGO_OPENIM_PASSWORD=${PASSWORD} \
--restart always \ --restart always \
mongo:6.0.2 --wiredTigerCacheSizeGB 1 --auth mongo:6.0.2 --wiredTigerCacheSizeGB 1 --auth
# Start Redis service # Start Redis service
docker run -d \ docker run -d \
--name redis \ --name redis \
-p 16379:6379 \ -p 16379:6379 \
-v "${DATA_DIR}/components/redis/data:/data" \ -v "${DATA_DIR}/components/redis/data:/data" \
-v "${DATA_DIR}/components/redis/config/redis.conf:/usr/local/redis/config/redis.conf" \ -v "${DATA_DIR}/components/redis/config/redis.conf:/usr/local/redis/config/redis.conf" \
-e TZ=Asia/Shanghai \ -e TZ=Asia/Shanghai \
--sysctl net.core.somaxconn=1024 \ --sysctl net.core.somaxconn=1024 \
--restart always \ --restart always \
redis:7.0.0 redis-server --requirepass ${PASSWORD} --appendonly yes redis:7.0.0 redis-server --requirepass ${PASSWORD} --appendonly yes
# Start Zookeeper service # Start Zookeeper service
docker run -d \ docker run -d \
--name zookeeper \ --name zookeeper \
-p 2181:2181 \ -p 2181:2181 \
-v "/etc/localtime:/etc/localtime" \ -v "/etc/localtime:/etc/localtime" \
-e TZ=Asia/Shanghai \ -e TZ=Asia/Shanghai \
--restart always \ --restart always \
wurstmeister/zookeeper wurstmeister/zookeeper
# Start Kafka service # Start Kafka service
docker run -d \ docker run -d \
--name kafka \ --name kafka \
-p 9092:9092 \ -p 9092:9092 \
-e TZ=Asia/Shanghai \ -e TZ=Asia/Shanghai \
-e KAFKA_BROKER_ID=0 \ -e KAFKA_BROKER_ID=0 \
-e KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 \ -e KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 \
-e KAFKA_CREATE_TOPICS="latestMsgToRedis:8:1,msgToPush:8:1,offlineMsgToMongoMysql:8:1" \ -e KAFKA_CREATE_TOPICS="latestMsgToRedis:8:1,msgToPush:8:1,offlineMsgToMongoMysql:8:1" \
-e KAFKA_ADVERTISED_LISTENERS="INSIDE://127.0.0.1:9092,OUTSIDE://103.116.45.174:9092" \ -e KAFKA_ADVERTISED_LISTENERS="INSIDE://127.0.0.1:9092,OUTSIDE://103.116.45.174:9092" \
-e KAFKA_LISTENERS="INSIDE://:9092,OUTSIDE://:9093" \ -e KAFKA_LISTENERS="INSIDE://:9092,OUTSIDE://:9093" \
-e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP="INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT" \ -e KAFKA_LISTENER_SECURITY_PROTOCOL_MAP="INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT" \
-e KAFKA_INTER_BROKER_LISTENER_NAME=INSIDE \ -e KAFKA_INTER_BROKER_LISTENER_NAME=INSIDE \
--restart always \ --restart always \
--link zookeeper \ --link zookeeper \
wurstmeister/kafka wurstmeister/kafka
# Start MinIO service # Start MinIO service
docker run -d \ docker run -d \
--name minio \ --name minio \
-p 10005:9000 \ -p 10005:9000 \
-p 9090:9090 \ -p 9090:9090 \
-v "/mnt/data:/data" \ -v "/mnt/data:/data" \
-v "/mnt/config:/root/.minio" \ -v "/mnt/config:/root/.minio" \
-e MINIO_ROOT_USER=${OPENIM_USER} \ -e MINIO_ROOT_USER=${OPENIM_USER} \
-e MINIO_ROOT_PASSWORD=${PASSWORD} \ -e MINIO_ROOT_PASSWORD=${PASSWORD} \
--restart always \ --restart always \
minio/minio server /data --console-address ':9090' minio/minio server /data --console-address ':9090'
+6 -6
View File
@@ -28,7 +28,7 @@ source "${OPENIM_ROOT}/scripts/lib/init.sh"
#TODO: Access to the OPENIM_IP networks outside, or you want to use the OPENIM_IP network #TODO: Access to the OPENIM_IP networks outside, or you want to use the OPENIM_IP network
# OPENIM_IP=127.0.0.1 # OPENIM_IP=127.0.0.1
if [ -z "${OPENIM_IP}" ]; then if [ -z "${OPENIM_IP}" ]; then
OPENIM_IP=$(openim::util::get_server_ip) OPENIM_IP=$(openim::util::get_server_ip)
fi fi
# config.gateway custom bridge modes # config.gateway custom bridge modes
@@ -37,9 +37,9 @@ fi
# fi # fi
function def() { function def() {
local var_name="$1" local var_name="$1"
local default_value="${2:-}" local default_value="${2:-}"
eval "readonly $var_name=\"\${$var_name:-$(printf '%q' "$default_value")}\"" eval "readonly $var_name=\"\${$var_name:-$(printf '%q' "$default_value")}\""
} }
# OpenIM Docker Compose 数据存储的默认路径 # OpenIM Docker Compose 数据存储的默认路径
@@ -89,8 +89,8 @@ SUBNET=$(echo $DOCKER_BRIDGE_SUBNET | cut -d '/' -f 2)
LAST_OCTET=$(echo $IP_PREFIX | cut -d '.' -f 4) LAST_OCTET=$(echo $IP_PREFIX | cut -d '.' -f 4)
generate_ip() { generate_ip() {
local NEW_IP="$(echo $IP_PREFIX | cut -d '.' -f 1-3).$((LAST_OCTET++))" local NEW_IP="$(echo $IP_PREFIX | cut -d '.' -f 1-3).$((LAST_OCTET++))"
echo $NEW_IP echo $NEW_IP
} }
LAST_OCTET=$((LAST_OCTET + 1)) LAST_OCTET=$((LAST_OCTET + 1))
DOCKER_BRIDGE_GATEWAY=$(generate_ip) DOCKER_BRIDGE_GATEWAY=$(generate_ip)
+63 -63
View File
@@ -21,17 +21,17 @@
# This tool is customized to meet the specific needs of OpenIM and resides in its separate repository. # This tool is customized to meet the specific needs of OpenIM and resides in its separate repository.
# It can be downloaded from the following link: # It can be downloaded from the following link:
# https://github.com/OpenIMSDK/Open-IM-Protoc/releases/tag/v1.0.0 # https://github.com/OpenIMSDK/Open-IM-Protoc/releases/tag/v1.0.0
# #
# About the tool: # About the tool:
# https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/protoc-tools.md # https://github.com/openimsdk/open-im-server/blob/main/docs/contrib/protoc-tools.md
# Download link (Windows): https://github.com/OpenIMSDK/Open-IM-Protoc/releases/download/v1.0.0/windows.zip # Download link (Windows): https://github.com/OpenIMSDK/Open-IM-Protoc/releases/download/v1.0.0/windows.zip
# Download link (Linux): https://github.com/OpenIMSDK/Open-IM-Protoc/releases/download/v1.0.0/linux.zip # Download link (Linux): https://github.com/OpenIMSDK/Open-IM-Protoc/releases/download/v1.0.0/linux.zip
# #
# Installation steps (taking Windows as an example): # Installation steps (taking Windows as an example):
# 1. Visit the above link and download the version suitable for Windows. # 1. Visit the above link and download the version suitable for Windows.
# 2. Extract the downloaded file. # 2. Extract the downloaded file.
# 3. Add the extracted tool to your PATH environment variable so that it can be run directly from the command line. # 3. Add the extracted tool to your PATH environment variable so that it can be run directly from the command line.
# #
# Note: The specific installation and usage instructions may vary based on the tool's actual implementation. It's advised to refer to official documentation. # Note: The specific installation and usage instructions may vary based on the tool's actual implementation. It's advised to refer to official documentation.
# -------------------------------------------------------------- # --------------------------------------------------------------
@@ -40,79 +40,79 @@ DOWNLOAD_DIR="/tmp/openim-protoc"
INSTALL_DIR="/usr/local/bin" INSTALL_DIR="/usr/local/bin"
function help_message { function help_message {
echo "Usage: ./install-protobuf.sh [option]" echo "Usage: ./install-protobuf.sh [option]"
echo "Options:" echo "Options:"
echo "-i, --install Install the OpenIM Protoc tool." echo "-i, --install Install the OpenIM Protoc tool."
echo "-u, --uninstall Uninstall the OpenIM Protoc tool." echo "-u, --uninstall Uninstall the OpenIM Protoc tool."
echo "-r, --reinstall Reinstall the OpenIM Protoc tool." echo "-r, --reinstall Reinstall the OpenIM Protoc tool."
echo "-c, --check Check if the OpenIM Protoc tool is installed." echo "-c, --check Check if the OpenIM Protoc tool is installed."
echo "-h, --help Display this help message." echo "-h, --help Display this help message."
} }
function install_protobuf { function install_protobuf {
echo "Installing OpenIM Protoc tool..." echo "Installing OpenIM Protoc tool..."
# Create temporary directory and download the zip file # Create temporary directory and download the zip file
mkdir -p $DOWNLOAD_DIR mkdir -p $DOWNLOAD_DIR
wget $PROTOC_DOWNLOAD_URL -O $DOWNLOAD_DIR/linux.zip wget $PROTOC_DOWNLOAD_URL -O $DOWNLOAD_DIR/linux.zip
# Unzip the file # Unzip the file
unzip -o $DOWNLOAD_DIR/linux.zip -d $DOWNLOAD_DIR unzip -o $DOWNLOAD_DIR/linux.zip -d $DOWNLOAD_DIR
# Move binaries to the install directory and make them executable # Move binaries to the install directory and make them executable
sudo cp $DOWNLOAD_DIR/linux/protoc $INSTALL_DIR/ sudo cp $DOWNLOAD_DIR/linux/protoc $INSTALL_DIR/
sudo cp $DOWNLOAD_DIR/linux/protoc-gen-go $INSTALL_DIR/ sudo cp $DOWNLOAD_DIR/linux/protoc-gen-go $INSTALL_DIR/
sudo chmod +x $INSTALL_DIR/protoc sudo chmod +x $INSTALL_DIR/protoc
sudo chmod +x $INSTALL_DIR/protoc-gen-go sudo chmod +x $INSTALL_DIR/protoc-gen-go
# Clean up # Clean up
rm -rf $DOWNLOAD_DIR rm -rf $DOWNLOAD_DIR
echo "OpenIM Protoc tool installed successfully!" echo "OpenIM Protoc tool installed successfully!"
} }
function uninstall_protobuf { function uninstall_protobuf {
echo "Uninstalling OpenIM Protoc tool..." echo "Uninstalling OpenIM Protoc tool..."
# Removing binaries from the install directory # Removing binaries from the install directory
sudo rm -f $INSTALL_DIR/protoc sudo rm -f $INSTALL_DIR/protoc
sudo rm -f $INSTALL_DIR/protoc-gen-go sudo rm -f $INSTALL_DIR/protoc-gen-go
echo "OpenIM Protoc tool uninstalled successfully!" echo "OpenIM Protoc tool uninstalled successfully!"
} }
function reinstall_protobuf { function reinstall_protobuf {
echo "Reinstalling OpenIM Protoc tool..." echo "Reinstalling OpenIM Protoc tool..."
uninstall_protobuf uninstall_protobuf
install_protobuf install_protobuf
} }
function check_protobuf { function check_protobuf {
echo "Checking for OpenIM Protoc tool installation..." echo "Checking for OpenIM Protoc tool installation..."
which protoc > /dev/null 2>&1 which protoc > /dev/null 2>&1
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
echo "OpenIM Protoc tool is installed." echo "OpenIM Protoc tool is installed."
else else
echo "OpenIM Protoc tool is not installed." echo "OpenIM Protoc tool is not installed."
fi fi
} }
while [ "$1" != "" ]; do while [ "$1" != "" ]; do
case $1 in case $1 in
-i | --install ) install_protobuf -i | --install ) install_protobuf
;; ;;
-u | --uninstall ) uninstall_protobuf -u | --uninstall ) uninstall_protobuf
;; ;;
-r | --reinstall ) reinstall_protobuf -r | --reinstall ) reinstall_protobuf
;; ;;
-c | --check ) check_protobuf -c | --check ) check_protobuf
;; ;;
-h | --help ) help_message -h | --help ) help_message
exit exit
;; ;;
* ) help_message * ) help_message
exit 1 exit 1
esac esac
shift shift
done done
+93 -93
View File
@@ -14,38 +14,38 @@
# limitations under the License. # limitations under the License.
# #
# OpenIM Server Installation Script # OpenIM Server Installation Script
# #
# Description: # Description:
# This script is designed to handle the installation, Is a deployment solution # This script is designed to handle the installation, Is a deployment solution
# that uses the Linux systen extension. uninstallation, and # that uses the Linux systen extension. uninstallation, and
# status checking of OpenIM components on the server. OpenIM is a presumed # status checking of OpenIM components on the server. OpenIM is a presumed
# communication or messaging platform based on the context. # communication or messaging platform based on the context.
# #
# Usage: # Usage:
# To utilize this script, you need to invoke it with specific commands # To utilize this script, you need to invoke it with specific commands
# and options as detailed below. # and options as detailed below.
# #
# Commands: # Commands:
# -i, --install : Use this command to initiate the installation of all # -i, --install : Use this command to initiate the installation of all
# OpenIM components. # OpenIM components.
# -u, --uninstall : Use this command to uninstall or remove all # -u, --uninstall : Use this command to uninstall or remove all
# OpenIM components from the server. # OpenIM components from the server.
# -s, --status : This command can be used to check and report the # -s, --status : This command can be used to check and report the
# current operational status of the installed OpenIM components. # current operational status of the installed OpenIM components.
# -h, --help : For any assistance or to view the available commands, # -h, --help : For any assistance or to view the available commands,
# use this command to display the help menu. # use this command to display the help menu.
# #
# Example Usage: # Example Usage:
# To install all OpenIM components: # To install all OpenIM components:
# ./scripts/install/install.sh -i # ./scripts/install/install.sh -i
# or # or
# ./scripts/install/install.sh --install # ./scripts/install/install.sh --install
# #
# Note: # Note:
# Ensure you have the necessary privileges to execute installation or # Ensure you have the necessary privileges to execute installation or
# uninstallation operations. It's generally recommended to take a backup # uninstallation operations. It's generally recommended to take a backup
# before making major changes. # before making major changes.
# #
############################################################################### ###############################################################################
OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P) OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
@@ -57,99 +57,99 @@ ${OPENIM_ROOT}/scripts/install/test.sh
# Detailed help function # Detailed help function
function openim::install::show_help() { function openim::install::show_help() {
echo "OpenIM Installer" echo "OpenIM Installer"
echo "Usage: $0 <command> [options]" echo "Usage: $0 <command> [options]"
echo "" echo ""
echo "Commands:" echo "Commands:"
echo " -i, --install Install all OpenIM components." echo " -i, --install Install all OpenIM components."
echo " -u, --uninstall Remove all OpenIM components." echo " -u, --uninstall Remove all OpenIM components."
echo " -s, --status Check the current status of OpenIM components." echo " -s, --status Check the current status of OpenIM components."
echo " -h, --help Show this help menu." echo " -h, --help Show this help menu."
echo "" echo ""
echo "Example: " echo "Example: "
echo " $0 -i Will install all OpenIM components." echo " $0 -i Will install all OpenIM components."
echo " $0 --install Same as above." echo " $0 --install Same as above."
} }
function openim::install::install_openim() { function openim::install::install_openim() {
openim::common::sudo "mkdir -p ${OPENIM_DATA_DIR} ${OPENIM_INSTALL_DIR} ${OPENIM_CONFIG_DIR} ${OPENIM_LOG_DIR}" openim::common::sudo "mkdir -p ${OPENIM_DATA_DIR} ${OPENIM_INSTALL_DIR} ${OPENIM_CONFIG_DIR} ${OPENIM_LOG_DIR}"
openim::log::info "check openim dependency" openim::log::info "check openim dependency"
openim::common::sudo "cp -r ${OPENIM_ROOT}/config/* ${OPENIM_CONFIG_DIR}/" openim::common::sudo "cp -r ${OPENIM_ROOT}/config/* ${OPENIM_CONFIG_DIR}/"
${OPENIM_ROOT}/scripts/genconfig.sh ${ENV_FILE} ${OPENIM_ROOT}/deployments/templates/config.yaml > ${OPENIM_CONFIG_DIR}/config.yaml ${OPENIM_ROOT}/scripts/genconfig.sh ${ENV_FILE} ${OPENIM_ROOT}/deployments/templates/config.yaml > ${OPENIM_CONFIG_DIR}/config.yaml
${OPENIM_ROOT}/scripts/genconfig.sh ${ENV_FILE} ${OPENIM_ROOT}/deployments/templates/prometheus.yml > ${OPENIM_CONFIG_DIR}/prometheus.yml ${OPENIM_ROOT}/scripts/genconfig.sh ${ENV_FILE} ${OPENIM_ROOT}/deployments/templates/prometheus.yml > ${OPENIM_CONFIG_DIR}/prometheus.yml
openim::util::check_ports ${OPENIM_DEPENDENCY_PORT_LISTARIES[@]} openim::util::check_ports ${OPENIM_DEPENDENCY_PORT_LISTARIES[@]}
${OPENIM_ROOT}/scripts/install/openim-msggateway.sh openim::msggateway::install || return 1 ${OPENIM_ROOT}/scripts/install/openim-msggateway.sh openim::msggateway::install || return 1
${OPENIM_ROOT}/scripts/install/openim-msgtransfer.sh openim::msgtransfer::install || return 1 ${OPENIM_ROOT}/scripts/install/openim-msgtransfer.sh openim::msgtransfer::install || return 1
${OPENIM_ROOT}/scripts/install/openim-push.sh openim::push::install || return 1 ${OPENIM_ROOT}/scripts/install/openim-push.sh openim::push::install || return 1
${OPENIM_ROOT}/scripts/install/openim-crontask.sh openim::crontask::install || return 1 ${OPENIM_ROOT}/scripts/install/openim-crontask.sh openim::crontask::install || return 1
${OPENIM_ROOT}/scripts/install/openim-rpc.sh openim::rpc::install || return 1 ${OPENIM_ROOT}/scripts/install/openim-rpc.sh openim::rpc::install || return 1
${OPENIM_ROOT}/scripts/install/openim-api.sh openim::api::install || return 1 ${OPENIM_ROOT}/scripts/install/openim-api.sh openim::api::install || return 1
openim::common::sudo "cp -r ${OPENIM_ROOT}/deployments/templates/openim.target /etc/systemd/system/openim.target" openim::common::sudo "cp -r ${OPENIM_ROOT}/deployments/templates/openim.target /etc/systemd/system/openim.target"
openim::common::sudo "systemctl daemon-reload" openim::common::sudo "systemctl daemon-reload"
openim::common::sudo "systemctl restart openim.target" openim::common::sudo "systemctl restart openim.target"
openim::common::sudo "systemctl enable openim.target" openim::common::sudo "systemctl enable openim.target"
openim::log::success "openim install success" openim::log::success "openim install success"
} }
function openim::uninstall::uninstall_openim() { function openim::uninstall::uninstall_openim() {
openim::log::info "uninstall openim" openim::log::info "uninstall openim"
${OPENIM_ROOT}/scripts/install/openim-msggateway.sh openim::msggateway::uninstall || return 1 ${OPENIM_ROOT}/scripts/install/openim-msggateway.sh openim::msggateway::uninstall || return 1
${OPENIM_ROOT}/scripts/install/openim-msgtransfer.sh openim::msgtransfer::uninstall || return 1 ${OPENIM_ROOT}/scripts/install/openim-msgtransfer.sh openim::msgtransfer::uninstall || return 1
${OPENIM_ROOT}/scripts/install/openim-push.sh openim::push::uninstall || return 1 ${OPENIM_ROOT}/scripts/install/openim-push.sh openim::push::uninstall || return 1
${OPENIM_ROOT}/scripts/install/openim-crontask.sh openim::crontask::uninstall || return 1 ${OPENIM_ROOT}/scripts/install/openim-crontask.sh openim::crontask::uninstall || return 1
${OPENIM_ROOT}/scripts/install/openim-rpc.sh openim::rpc::uninstall || return 1 ${OPENIM_ROOT}/scripts/install/openim-rpc.sh openim::rpc::uninstall || return 1
${OPENIM_ROOT}/scripts/install/openim-api.sh openim::api::uninstall || return 1 ${OPENIM_ROOT}/scripts/install/openim-api.sh openim::api::uninstall || return 1
set +o errexit set +o errexit
openim::common::sudo "systemctl stop openim.target" openim::common::sudo "systemctl stop openim.target"
openim::common::sudo "systemctl disable openim.target" openim::common::sudo "systemctl disable openim.target"
openim::common::sudo "rm -f /etc/systemd/system/openim.target" openim::common::sudo "rm -f /etc/systemd/system/openim.target"
set -o errexit set -o errexit
openim::log::success "openim uninstall success" openim::log::success "openim uninstall success"
} }
function openim::install::status() { function openim::install::status() {
openim::log::info "check openim status" openim::log::info "check openim status"
${OPENIM_ROOT}/scripts/install/openim-msggateway.sh openim::msggateway::status || return 1 ${OPENIM_ROOT}/scripts/install/openim-msggateway.sh openim::msggateway::status || return 1
${OPENIM_ROOT}/scripts/install/openim-msgtransfer.sh openim::msgtransfer::status || return 1 ${OPENIM_ROOT}/scripts/install/openim-msgtransfer.sh openim::msgtransfer::status || return 1
${OPENIM_ROOT}/scripts/install/openim-push.sh openim::push::status || return 1 ${OPENIM_ROOT}/scripts/install/openim-push.sh openim::push::status || return 1
${OPENIM_ROOT}/scripts/install/openim-crontask.sh openim::crontask::status || return 1 ${OPENIM_ROOT}/scripts/install/openim-crontask.sh openim::crontask::status || return 1
${OPENIM_ROOT}/scripts/install/openim-rpc.sh openim::rpc::status || return 1 ${OPENIM_ROOT}/scripts/install/openim-rpc.sh openim::rpc::status || return 1
${OPENIM_ROOT}/scripts/install/openim-api.sh openim::api::status || return 1 ${OPENIM_ROOT}/scripts/install/openim-api.sh openim::api::status || return 1
openim::log::success "openim status success" openim::log::success "openim status success"
} }
# If no arguments are provided, show help # If no arguments are provided, show help
if [[ $# -eq 0 ]]; then if [[ $# -eq 0 ]]; then
openim::install::show_help openim::install::show_help
exit 0 exit 0
fi fi
# Argument parsing to call functions based on user input # Argument parsing to call functions based on user input
while (( "$#" )); do while (( "$#" )); do
case "$1" in case "$1" in
-i|--install) -i|--install)
openim::install::install_openim openim::install::install_openim
shift shift
;; ;;
-u|--uninstall) -u|--uninstall)
openim::uninstall::uninstall_openim openim::uninstall::uninstall_openim
shift shift
;; ;;
-s|--status) -s|--status)
openim::install::status openim::install::status
shift shift
;; ;;
-h|--help|*) -h|--help|*)
openim::install::show_help openim::install::show_help
exit 0 exit 0
;; ;;
esac esac
done done
+76 -76
View File
@@ -34,55 +34,55 @@ readonly OPENIM_API_SERVICE_TARGETS=(
readonly OPENIM_API_SERVICE_LISTARIES=("${OPENIM_API_SERVICE_TARGETS[@]##*/}") readonly OPENIM_API_SERVICE_LISTARIES=("${OPENIM_API_SERVICE_TARGETS[@]##*/}")
function openim::api::start() { function openim::api::start() {
echo "++ OPENIM_API_SERVICE_LISTARIES: ${OPENIM_API_SERVICE_LISTARIES[@]}" echo "++ OPENIM_API_SERVICE_LISTARIES: ${OPENIM_API_SERVICE_LISTARIES[@]}"
echo "++ OPENIM_API_PORT_LISTARIES: ${OPENIM_API_PORT_LISTARIES[@]}" echo "++ OPENIM_API_PORT_LISTARIES: ${OPENIM_API_PORT_LISTARIES[@]}"
echo "++ OpenIM API config path: ${OPENIM_API_CONFIG}" echo "++ OpenIM API config path: ${OPENIM_API_CONFIG}"
openim::log::info "Starting ${SERVER_NAME} ..." openim::log::info "Starting ${SERVER_NAME} ..."
printf "+------------------------+--------------+\n" printf "+------------------------+--------------+\n"
printf "| Service Name | Port |\n" printf "| Service Name | Port |\n"
printf "+------------------------+--------------+\n" printf "+------------------------+--------------+\n"
length=${#OPENIM_API_SERVICE_LISTARIES[@]} length=${#OPENIM_API_SERVICE_LISTARIES[@]}
for ((i=0; i<$length; i++)); do for ((i=0; i<$length; i++)); do
printf "| %-22s | %6s |\n" "${OPENIM_API_SERVICE_LISTARIES[$i]}" "${OPENIM_API_PORT_LISTARIES[$i]}" printf "| %-22s | %6s |\n" "${OPENIM_API_SERVICE_LISTARIES[$i]}" "${OPENIM_API_PORT_LISTARIES[$i]}"
printf "+------------------------+--------------+\n" printf "+------------------------+--------------+\n"
done done
# start all api services # start all api services
for ((i = 0; i < ${#OPENIM_API_SERVICE_LISTARIES[*]}; i++)); do for ((i = 0; i < ${#OPENIM_API_SERVICE_LISTARIES[*]}; i++)); do
openim::util::stop_services_on_ports ${OPENIM_API_PORT_LISTARIES[$i]} openim::util::stop_services_on_ports ${OPENIM_API_PORT_LISTARIES[$i]}
openim::log::info "OpenIM ${OPENIM_API_SERVICE_LISTARIES[$i]} config path: ${OPENIM_API_CONFIG}" openim::log::info "OpenIM ${OPENIM_API_SERVICE_LISTARIES[$i]} config path: ${OPENIM_API_CONFIG}"
# Get the service and Prometheus ports. # Get the service and Prometheus ports.
OPENIM_API_SERVICE_PORTS=( $(openim::util::list-to-string ${OPENIM_API_PORT_LISTARIES[$i]}) ) OPENIM_API_SERVICE_PORTS=( $(openim::util::list-to-string ${OPENIM_API_PORT_LISTARIES[$i]}) )
# TODO Only one port is supported. An error occurs on multiple ports # TODO Only one port is supported. An error occurs on multiple ports
if [ ${#OPENIM_API_SERVICE_PORTS[@]} -ne 1 ]; then if [ ${#OPENIM_API_SERVICE_PORTS[@]} -ne 1 ]; then
openim::log::error_exit "Set only one port for ${OPENIM_API_SERVICE_LISTARIES[$i]} service." openim::log::error_exit "Set only one port for ${OPENIM_API_SERVICE_LISTARIES[$i]} service."
fi fi
for ((j = 0; j < ${#OPENIM_API_SERVICE_PORTS[@]}; j++)); do for ((j = 0; j < ${#OPENIM_API_SERVICE_PORTS[@]}; j++)); do
openim::log::info "Starting ${OPENIM_API_SERVICE_LISTARIES[$i]} service, port: ${OPENIM_API_SERVICE_PORTS[j]}, binary root: ${OPENIM_OUTPUT_HOSTBIN}/${OPENIM_API_SERVICE_LISTARIES[$i]}" openim::log::info "Starting ${OPENIM_API_SERVICE_LISTARIES[$i]} service, port: ${OPENIM_API_SERVICE_PORTS[j]}, binary root: ${OPENIM_OUTPUT_HOSTBIN}/${OPENIM_API_SERVICE_LISTARIES[$i]}"
openim::api::start_service "${OPENIM_API_SERVICE_LISTARIES[$i]}" "${OPENIM_API_PORT_LISTARIES[j]}" openim::api::start_service "${OPENIM_API_SERVICE_LISTARIES[$i]}" "${OPENIM_API_PORT_LISTARIES[j]}"
sleep 2 sleep 2
done
done done
done
OPENIM_API_PORT_STRINGARIES=( $(openim::util::list-to-string ${OPENIM_API_PORT_LISTARIES[@]}) )
OPENIM_API_PORT_STRINGARIES=( $(openim::util::list-to-string ${OPENIM_API_PORT_LISTARIES[@]}) ) openim::util::check_ports ${OPENIM_API_PORT_STRINGARIES[@]}
openim::util::check_ports ${OPENIM_API_PORT_STRINGARIES[@]}
} }
function openim::api::start_service() { function openim::api::start_service() {
local binary_name="$1" local binary_name="$1"
local service_port="$2" local service_port="$2"
local prometheus_port="$3" local prometheus_port="$3"
local cmd="${OPENIM_OUTPUT_HOSTBIN}/${binary_name} --port ${service_port} -c ${OPENIM_API_CONFIG}" local cmd="${OPENIM_OUTPUT_HOSTBIN}/${binary_name} --port ${service_port} -c ${OPENIM_API_CONFIG}"
nohup ${cmd} >> "${LOG_FILE}" 2>&1 & nohup ${cmd} >> "${LOG_FILE}" 2>&1 &
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
openim::log::error_exit "Failed to start ${binary_name} on port ${service_port}." openim::log::error_exit "Failed to start ${binary_name} on port ${service_port}."
fi fi
@@ -100,61 +100,61 @@ EOF
# install openim-api # install openim-api
function openim::api::install() { function openim::api::install() {
openim::log::info "Installing ${SERVER_NAME} ..." openim::log::info "Installing ${SERVER_NAME} ..."
pushd "${OPENIM_ROOT}" pushd "${OPENIM_ROOT}"
# 1. Build openim-api # 1. Build openim-api
make build BINS=${SERVER_NAME} make build BINS=${SERVER_NAME}
openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}" openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}" openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}"
# 2. Generate and install the openim-api configuration file (config) # 2. Generate and install the openim-api configuration file (config)
openim::log::status "${SERVER_NAME} config file: ${OPENIM_CONFIG_DIR}/config.yaml" openim::log::status "${SERVER_NAME} config file: ${OPENIM_CONFIG_DIR}/config.yaml"
# 3. Create and install the ${SERVER_NAME} systemd unit file # 3. Create and install the ${SERVER_NAME} systemd unit file
echo ${LINUX_PASSWORD} | sudo -S bash -c \ echo ${LINUX_PASSWORD} | sudo -S bash -c \
"SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}" "SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}"
openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}" openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}"
# 4. Start the openim-api service # 4. Start the openim-api service
openim::common::sudo "systemctl daemon-reload" openim::common::sudo "systemctl daemon-reload"
openim::common::sudo "systemctl restart ${SERVER_NAME}" openim::common::sudo "systemctl restart ${SERVER_NAME}"
openim::common::sudo "systemctl enable ${SERVER_NAME}" openim::common::sudo "systemctl enable ${SERVER_NAME}"
openim::api::status || return 1 openim::api::status || return 1
openim::api::info openim::api::info
openim::log::info "install ${SERVER_NAME} successfully" openim::log::info "install ${SERVER_NAME} successfully"
popd popd
} }
# Unload # Unload
function openim::api::uninstall() { function openim::api::uninstall() {
openim::log::info "Uninstalling ${SERVER_NAME} ..." openim::log::info "Uninstalling ${SERVER_NAME} ..."
set +o errexit set +o errexit
openim::common::sudo "systemctl stop ${SERVER_NAME}" openim::common::sudo "systemctl stop ${SERVER_NAME}"
openim::common::sudo "systemctl disable ${SERVER_NAME}" openim::common::sudo "systemctl disable ${SERVER_NAME}"
openim::common::sudo "rm -f ${OPENIM_INSTALL_DIR}/${SERVER_NAME}" openim::common::sudo "rm -f ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
openim::common::sudo "rm -f ${OPENIM_CONFIG_DIR}/${SERVER_NAME}.yaml" openim::common::sudo "rm -f ${OPENIM_CONFIG_DIR}/${SERVER_NAME}.yaml"
openim::common::sudo "rm -f /etc/systemd/system/${SERVER_NAME}.service" openim::common::sudo "rm -f /etc/systemd/system/${SERVER_NAME}.service"
set -o errexit set -o errexit
openim::log::info "uninstall ${SERVER_NAME} successfully" openim::log::info "uninstall ${SERVER_NAME} successfully"
} }
# Status Check # Status Check
function openim::api::status() { function openim::api::status() {
openim::log::info "Checking ${SERVER_NAME} status ..." openim::log::info "Checking ${SERVER_NAME} status ..."
# Check the running status of the ${SERVER_NAME}. If active (running) is displayed, the ${SERVER_NAME} is started successfully. # Check the running status of the ${SERVER_NAME}. If active (running) is displayed, the ${SERVER_NAME} is started successfully.
systemctl status ${SERVER_NAME}|grep -q 'active' || { systemctl status ${SERVER_NAME}|grep -q 'active' || {
openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly" openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly"
return 1 return 1
} }
openim::util::check_ports ${OPENIM_API_PORT_LISTARIES[@]} openim::util::check_ports ${OPENIM_API_PORT_LISTARIES[@]}
} }
if [[ "$*" =~ openim::api:: ]];then if [[ "$*" =~ openim::api:: ]];then
eval $* eval $*
fi fi
+21 -21
View File
@@ -13,12 +13,12 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# OpenIM CronTask Control Script # OpenIM CronTask Control Script
# #
# Description: # Description:
# This script provides a control interface for the OpenIM CronTask service within a Linux environment. It supports two installation methods: installation via function calls to systemctl, and direct installation through background processes. # This script provides a control interface for the OpenIM CronTask service within a Linux environment. It supports two installation methods: installation via function calls to systemctl, and direct installation through background processes.
# #
# Features: # Features:
# 1. Robust error handling leveraging Bash built-ins such as 'errexit', 'nounset', and 'pipefail'. # 1. Robust error handling leveraging Bash built-ins such as 'errexit', 'nounset', and 'pipefail'.
# 2. Capability to source common utility functions and configurations, ensuring environmental consistency. # 2. Capability to source common utility functions and configurations, ensuring environmental consistency.
@@ -30,13 +30,13 @@
# 1. Direct Script Execution: # 1. Direct Script Execution:
# This will start the OpenIM CronTask directly through a background process. # This will start the OpenIM CronTask directly through a background process.
# Example: ./openim-crontask.sh openim::crontask::start # Example: ./openim-crontask.sh openim::crontask::start
# #
# 2. Controlling through Functions for systemctl operations: # 2. Controlling through Functions for systemctl operations:
# Specific operations like installation, uninstallation, and status check can be executed by passing the respective function name as an argument to the script. # Specific operations like installation, uninstallation, and status check can be executed by passing the respective function name as an argument to the script.
# Example: ./openim-crontask.sh openim::crontask::install # Example: ./openim-crontask.sh openim::crontask::install
# #
# Note: Ensure that the appropriate permissions and environmental variables are set prior to script execution. # Note: Ensure that the appropriate permissions and environmental variables are set prior to script execution.
# #
OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P) OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
[[ -z ${COMMON_SOURCED} ]] && source "${OPENIM_ROOT}"/scripts/install/common.sh [[ -z ${COMMON_SOURCED} ]] && source "${OPENIM_ROOT}"/scripts/install/common.sh
@@ -44,14 +44,14 @@ OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
SERVER_NAME="openim-crontask" SERVER_NAME="openim-crontask"
function openim::crontask::start() { function openim::crontask::start() {
openim::log::info "Start OpenIM Cron, binary root: ${SERVER_NAME}" openim::log::info "Start OpenIM Cron, binary root: ${SERVER_NAME}"
openim::log::status "Start OpenIM Cron, path: ${OPENIM_CRONTASK_BINARY}" openim::log::status "Start OpenIM Cron, path: ${OPENIM_CRONTASK_BINARY}"
openim::util::stop_services_with_name ${OPENIM_CRONTASK_BINARY} openim::util::stop_services_with_name ${OPENIM_CRONTASK_BINARY}
openim::log::status "start cron_task process, path: ${OPENIM_CRONTASK_BINARY}" openim::log::status "start cron_task process, path: ${OPENIM_CRONTASK_BINARY}"
nohup ${OPENIM_CRONTASK_BINARY} -c ${OPENIM_PUSH_CONFIG} >> ${LOG_FILE} 2>&1 & nohup ${OPENIM_CRONTASK_BINARY} -c ${OPENIM_PUSH_CONFIG} >> ${LOG_FILE} 2>&1 &
openim::util::check_process_names ${SERVER_NAME} openim::util::check_process_names ${SERVER_NAME}
} }
###################################### Linux Systemd ###################################### ###################################### Linux Systemd ######################################
@@ -67,28 +67,28 @@ EOF
# install openim-crontask # install openim-crontask
function openim::crontask::install() { function openim::crontask::install() {
pushd "${OPENIM_ROOT}" pushd "${OPENIM_ROOT}"
# 1. Build openim-crontask # 1. Build openim-crontask
make build BINS=${SERVER_NAME} make build BINS=${SERVER_NAME}
openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}" openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}" openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}"
# 2. Generate and install the openim-crontask configuration file (openim-crontask.yaml) # 2. Generate and install the openim-crontask configuration file (openim-crontask.yaml)
openim::log::status "${SERVER_NAME} config file: ${OPENIM_CONFIG_DIR}/config.yaml" openim::log::status "${SERVER_NAME} config file: ${OPENIM_CONFIG_DIR}/config.yaml"
# 3. Create and install the ${SERVER_NAME} systemd unit file # 3. Create and install the ${SERVER_NAME} systemd unit file
echo ${LINUX_PASSWORD} | sudo -S bash -c \ echo ${LINUX_PASSWORD} | sudo -S bash -c \
"SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}" "SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}"
openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}" openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}"
# 4. Start the openim-crontask service # 4. Start the openim-crontask service
openim::common::sudo "systemctl daemon-reload" openim::common::sudo "systemctl daemon-reload"
openim::common::sudo "systemctl restart ${SERVER_NAME}" openim::common::sudo "systemctl restart ${SERVER_NAME}"
openim::common::sudo "systemctl enable ${SERVER_NAME}" openim::common::sudo "systemctl enable ${SERVER_NAME}"
openim::crontask::status || return 1 openim::crontask::status || return 1
openim::crontask::info openim::crontask::info
openim::log::info "install ${SERVER_NAME} successfully" openim::log::info "install ${SERVER_NAME} successfully"
popd popd
} }
+32 -32
View File
@@ -17,7 +17,7 @@
# #
# Description: # Description:
# This script manages the man pages for the OpenIM software suite. # This script manages the man pages for the OpenIM software suite.
# It provides facilities to install, uninstall, and verify the # It provides facilities to install, uninstall, and verify the
# installation status of the man pages related to OpenIM components. # installation status of the man pages related to OpenIM components.
# #
# Usage: # Usage:
@@ -26,15 +26,15 @@
# ./openim-man.sh openim::man::status - Check installation status # ./openim-man.sh openim::man::status - Check installation status
# #
# Dependencies: # Dependencies:
# - Assumes there's a common.sh in "${OPENIM_ROOT}/scripts/install/" # - Assumes there's a common.sh in "${OPENIM_ROOT}/scripts/install/"
# containing shared functions and variables. # containing shared functions and variables.
# - Relies on the script "${OPENIM_ROOT}/scripts/update-generated-docs.sh" # - Relies on the script "${OPENIM_ROOT}/scripts/update-generated-docs.sh"
# to generate the man pages. # to generate the man pages.
# #
# Notes: # Notes:
# - This script must be run with appropriate permissions to modify the # - This script must be run with appropriate permissions to modify the
# system man directories. # system man directories.
# - Always ensure you're in the script's directory or provide the correct # - Always ensure you're in the script's directory or provide the correct
# path when executing. # path when executing.
################################################################################ ################################################################################
@@ -54,43 +54,43 @@ EOF
# Install the man pages for openim # Install the man pages for openim
function openim::man::install() { function openim::man::install() {
# Navigate to the openim root directory # Navigate to the openim root directory
pushd "${OPENIM_ROOT}" > /dev/null pushd "${OPENIM_ROOT}" > /dev/null
# Generate man pages for each component # Generate man pages for each component
"${OPENIM_ROOT}/scripts/update-generated-docs.sh" "${OPENIM_ROOT}/scripts/update-generated-docs.sh"
openim::common::sudo "cp docs/man/man1/* /usr/share/man/man1/" openim::common::sudo "cp docs/man/man1/* /usr/share/man/man1/"
# Verify installation status # Verify installation status
if openim::man::status; then if openim::man::status; then
openim::log::info "Installed openim-server man page successfully" openim::log::info "Installed openim-server man page successfully"
openim::man::info openim::man::info
fi fi
# Return to the original directory # Return to the original directory
popd > /dev/null popd > /dev/null
} }
# Uninstall the man pages for openim # Uninstall the man pages for openim
function openim::man::uninstall() { function openim::man::uninstall() {
# Turn off exit-on-error temporarily to handle non-existing files gracefully # Turn off exit-on-error temporarily to handle non-existing files gracefully
set +o errexit set +o errexit
openim::common::sudo "rm -f /usr/share/man/man1/openim-*" openim::common::sudo "rm -f /usr/share/man/man1/openim-*"
set -o errexit set -o errexit
openim::log::info "Uninstalled openim man pages successfully" openim::log::info "Uninstalled openim man pages successfully"
} }
# Check the installation status of the man pages # Check the installation status of the man pages
function openim::man::status() { function openim::man::status() {
if ! ls /usr/share/man/man1/openim-* &> /dev/null; then if ! ls /usr/share/man/man1/openim-* &> /dev/null; then
openim::log::error "OpenIM man files not found. Perhaps they were not installed correctly." openim::log::error "OpenIM man files not found. Perhaps they were not installed correctly."
return 1 return 1
fi fi
return 0 return 0
} }
# Execute the appropriate function based on the given arguments # Execute the appropriate function based on the given arguments
if [[ "$*" =~ openim::man:: ]]; then if [[ "$*" =~ openim::man:: ]]; then
eval "$*" eval "$*"
fi fi
+9 -9
View File
@@ -26,19 +26,19 @@ openim::util::set_max_fd 200000
SERVER_NAME="openim-msggateway" SERVER_NAME="openim-msggateway"
function openim::msggateway::start() { function openim::msggateway::start() {
openim::log::info "Start OpenIM Msggateway, binary root: ${SERVER_NAME}" openim::log::info "Start OpenIM Msggateway, binary root: ${SERVER_NAME}"
openim::log::status "Start OpenIM Msggateway, path: ${OPENIM_MSGGATEWAY_BINARY}" openim::log::status "Start OpenIM Msggateway, path: ${OPENIM_MSGGATEWAY_BINARY}"
openim::util::stop_services_with_name ${OPENIM_MSGGATEWAY_BINARY} openim::util::stop_services_with_name ${OPENIM_MSGGATEWAY_BINARY}
# OpenIM message gateway service port # OpenIM message gateway service port
OPENIM_MESSAGE_GATEWAY_PORTS=$(openim::util::list-to-string ${OPENIM_MESSAGE_GATEWAY_PORT} ) OPENIM_MESSAGE_GATEWAY_PORTS=$(openim::util::list-to-string ${OPENIM_MESSAGE_GATEWAY_PORT} )
read -a OPENIM_MSGGATEWAY_PORTS_ARRAY <<< ${OPENIM_MESSAGE_GATEWAY_PORTS} read -a OPENIM_MSGGATEWAY_PORTS_ARRAY <<< ${OPENIM_MESSAGE_GATEWAY_PORTS}
openim::util::stop_services_on_ports ${OPENIM_MSGGATEWAY_PORTS_ARRAY[*]} openim::util::stop_services_on_ports ${OPENIM_MSGGATEWAY_PORTS_ARRAY[*]}
# OpenIM WS port # OpenIM WS port
OPENIM_WS_PORTS=$(openim::util::list-to-string ${OPENIM_WS_PORT} ) OPENIM_WS_PORTS=$(openim::util::list-to-string ${OPENIM_WS_PORT} )
read -a OPENIM_WS_PORTS_ARRAY <<< ${OPENIM_WS_PORTS} read -a OPENIM_WS_PORTS_ARRAY <<< ${OPENIM_WS_PORTS}
# Message Gateway Prometheus port of the service # Message Gateway Prometheus port of the service
MSG_GATEWAY_PROM_PORTS=$(openim::util::list-to-string ${MSG_GATEWAY_PROM_PORT} ) MSG_GATEWAY_PROM_PORTS=$(openim::util::list-to-string ${MSG_GATEWAY_PROM_PORT} )
read -a MSG_GATEWAY_PROM_PORTS_ARRAY <<< ${MSG_GATEWAY_PROM_PORTS} read -a MSG_GATEWAY_PROM_PORTS_ARRAY <<< ${MSG_GATEWAY_PROM_PORTS}
@@ -123,7 +123,7 @@ function openim::msggateway::status() {
# Check the running status of the ${SERVER_NAME}. If active (running) is displayed, the ${SERVER_NAME} is started successfully. # Check the running status of the ${SERVER_NAME}. If active (running) is displayed, the ${SERVER_NAME} is started successfully.
systemctl status ${SERVER_NAME}|grep -q 'active' || { systemctl status ${SERVER_NAME}|grep -q 'active' || {
openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly" openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly"
return 1 return 1
} }
+56 -56
View File
@@ -28,59 +28,59 @@ openim::util::set_max_fd 200000
SERVER_NAME="openim-msgtransfer" SERVER_NAME="openim-msgtransfer"
function openim::msgtransfer::start() { function openim::msgtransfer::start() {
openim::log::info "Start OpenIM Msggateway, binary root: ${SERVER_NAME}" openim::log::info "Start OpenIM Msggateway, binary root: ${SERVER_NAME}"
openim::log::status "Start OpenIM Msggateway, path: ${OPENIM_MSGTRANSFER_BINARY}" openim::log::status "Start OpenIM Msggateway, path: ${OPENIM_MSGTRANSFER_BINARY}"
openim::util::stop_services_with_name ${OPENIM_MSGTRANSFER_BINARY} openim::util::stop_services_with_name ${OPENIM_MSGTRANSFER_BINARY}
# Message Transfer Prometheus port list # Message Transfer Prometheus port list
MSG_TRANSFER_PROM_PORTS=(openim::util::list-to-string ${MSG_TRANSFER_PROM_PORT} ) MSG_TRANSFER_PROM_PORTS=(openim::util::list-to-string ${MSG_TRANSFER_PROM_PORT} )
openim::log::status "OpenIM Prometheus ports: ${MSG_TRANSFER_PROM_PORTS[*]}" openim::log::status "OpenIM Prometheus ports: ${MSG_TRANSFER_PROM_PORTS[*]}"
openim::log::status "OpenIM Msggateway config path: ${OPENIM_MSGTRANSFER_CONFIG}" openim::log::status "OpenIM Msggateway config path: ${OPENIM_MSGTRANSFER_CONFIG}"
openim::log::info "openim maggateway num: ${OPENIM_MSGGATEWAY_NUM}" openim::log::info "openim maggateway num: ${OPENIM_MSGGATEWAY_NUM}"
if [ "${OPENIM_MSGGATEWAY_NUM}" -lt 1 ]; then if [ "${OPENIM_MSGGATEWAY_NUM}" -lt 1 ]; then
opeim::log::error_exit "OPENIM_MSGGATEWAY_NUM must be greater than 0" opeim::log::error_exit "OPENIM_MSGGATEWAY_NUM must be greater than 0"
fi
if [ ${OPENIM_MSGGATEWAY_NUM} -ne $((${#MSG_TRANSFER_PROM_PORTS[@]} - 1)) ]; then
openim::log::error_exit "OPENIM_MSGGATEWAY_NUM must be equal to the number of MSG_TRANSFER_PROM_PORTS"
fi
for (( i=0; i<$OPENIM_MSGGATEWAY_NUM; i++ )) do
openim::log::info "prometheus port: ${MSG_TRANSFER_PROM_PORTS[$i]}"
PROMETHEUS_PORT_OPTION=""
if [[ -n "${OPENIM_PROMETHEUS_PORTS[$i]}" ]]; then
PROMETHEUS_PORT_OPTION="--prometheus_port ${OPENIM_PROMETHEUS_PORTS[$i]}"
fi fi
nohup ${OPENIM_MSGTRANSFER_BINARY} ${PROMETHEUS_PORT_OPTION} -c ${OPENIM_MSGTRANSFER_CONFIG} -n ${i}>> ${LOG_FILE} 2>&1 &
done if [ ${OPENIM_MSGGATEWAY_NUM} -ne $((${#MSG_TRANSFER_PROM_PORTS[@]} - 1)) ]; then
openim::log::error_exit "OPENIM_MSGGATEWAY_NUM must be equal to the number of MSG_TRANSFER_PROM_PORTS"
openim::util::check_process_names "${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME}" fi
for (( i=0; i<$OPENIM_MSGGATEWAY_NUM; i++ )) do
openim::log::info "prometheus port: ${MSG_TRANSFER_PROM_PORTS[$i]}"
PROMETHEUS_PORT_OPTION=""
if [[ -n "${OPENIM_PROMETHEUS_PORTS[$i]}" ]]; then
PROMETHEUS_PORT_OPTION="--prometheus_port ${OPENIM_PROMETHEUS_PORTS[$i]}"
fi
nohup ${OPENIM_MSGTRANSFER_BINARY} ${PROMETHEUS_PORT_OPTION} -c ${OPENIM_MSGTRANSFER_CONFIG} -n ${i}>> ${LOG_FILE} 2>&1 &
done
openim::util::check_process_names "${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME}"
} }
function openim::msgtransfer::check() { function openim::msgtransfer::check() {
PIDS=$(pgrep -f "${OPENIM_OUTPUT_HOSTBIN}/openim-msgtransfer") PIDS=$(pgrep -f "${OPENIM_OUTPUT_HOSTBIN}/openim-msgtransfer")
NUM_PROCESSES=$(echo "$PIDS" | wc -l) NUM_PROCESSES=$(echo "$PIDS" | wc -l)
if [ "$NUM_PROCESSES" -eq "$OPENIM_MSGGATEWAY_NUM" ]; then if [ "$NUM_PROCESSES" -eq "$OPENIM_MSGGATEWAY_NUM" ]; then
openim::log::info "Found $OPENIM_MSGGATEWAY_NUM processes named $OPENIM_OUTPUT_HOSTBIN" openim::log::info "Found $OPENIM_MSGGATEWAY_NUM processes named $OPENIM_OUTPUT_HOSTBIN"
for PID in $PIDS; do for PID in $PIDS; do
if [[ "$OSTYPE" == "linux-gnu"* ]]; then if [[ "$OSTYPE" == "linux-gnu"* ]]; then
ps -p $PID -o pid,cmd ps -p $PID -o pid,cmd
elif [[ "$OSTYPE" == "darwin"* ]]; then elif [[ "$OSTYPE" == "darwin"* ]]; then
ps -p $PID -o pid,comm ps -p $PID -o pid,comm
else else
openim::log::error "Unsupported OS type: $OSTYPE" openim::log::error "Unsupported OS type: $OSTYPE"
fi fi
done done
else else
openim::log::error_exit "Expected $OPENIM_MSGGATEWAY_NUM openim msgtransfer processes, but found $NUM_PROCESSES msgtransfer processes." openim::log::error_exit "Expected $OPENIM_MSGGATEWAY_NUM openim msgtransfer processes, but found $NUM_PROCESSES msgtransfer processes."
fi fi
} }
###################################### Linux Systemd ###################################### ###################################### Linux Systemd ######################################
@@ -96,30 +96,30 @@ EOF
# install openim-msgtransfer # install openim-msgtransfer
function openim::msgtransfer::install() { function openim::msgtransfer::install() {
pushd "${OPENIM_ROOT}" pushd "${OPENIM_ROOT}"
# 1. Build openim-msgtransfer # 1. Build openim-msgtransfer
make build BINS=${SERVER_NAME} make build BINS=${SERVER_NAME}
openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}" openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}" openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}"
openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/bin/${SERVER_NAME}" openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/bin/${SERVER_NAME}"
# 2. Generate and install the openim-msgtransfer configuration file (openim-msgtransfer.yaml) # 2. Generate and install the openim-msgtransfer configuration file (openim-msgtransfer.yaml)
# nono # nono
# 3. Create and install the ${SERVER_NAME} systemd unit file # 3. Create and install the ${SERVER_NAME} systemd unit file
echo ${LINUX_PASSWORD} | sudo -S bash -c \ echo ${LINUX_PASSWORD} | sudo -S bash -c \
"SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}" "SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}"
openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}" openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}"
# 4. Start the openim-msgtransfer service # 4. Start the openim-msgtransfer service
openim::common::sudo "systemctl daemon-reload" openim::common::sudo "systemctl daemon-reload"
openim::common::sudo "systemctl restart ${SERVER_NAME}" openim::common::sudo "systemctl restart ${SERVER_NAME}"
openim::common::sudo "systemctl enable ${SERVER_NAME}" openim::common::sudo "systemctl enable ${SERVER_NAME}"
openim::msgtransfer::status || return 1 openim::msgtransfer::status || return 1
openim::msgtransfer::info openim::msgtransfer::info
openim::log::info "install ${SERVER_NAME} successfully" openim::log::info "install ${SERVER_NAME} successfully"
popd popd
} }
+35 -35
View File
@@ -14,10 +14,10 @@
# limitations under the License. # limitations under the License.
# #
# OpenIM Push Control Script # OpenIM Push Control Script
# #
# Description: # Description:
# This script provides a control interface for the OpenIM Push service within a Linux environment. It supports two installation methods: installation via function calls to systemctl, and direct installation through background processes. # This script provides a control interface for the OpenIM Push service within a Linux environment. It supports two installation methods: installation via function calls to systemctl, and direct installation through background processes.
# #
# Features: # Features:
# 1. Robust error handling leveraging Bash built-ins such as 'errexit', 'nounset', and 'pipefail'. # 1. Robust error handling leveraging Bash built-ins such as 'errexit', 'nounset', and 'pipefail'.
# 2. Capability to source common utility functions and configurations, ensuring environmental consistency. # 2. Capability to source common utility functions and configurations, ensuring environmental consistency.
@@ -29,7 +29,7 @@
# 1. Direct Script Execution: # 1. Direct Script Execution:
# This will start the OpenIM push directly through a background process. # This will start the OpenIM push directly through a background process.
# Example: ./openim-push.sh # Example: ./openim-push.sh
# #
# 2. Controlling through Functions for systemctl operations: # 2. Controlling through Functions for systemctl operations:
# Specific operations like installation, uninstallation, and status check can be executed by passing the respective function name as an argument to the script. # Specific operations like installation, uninstallation, and status check can be executed by passing the respective function name as an argument to the script.
# Example: ./openim-push.sh openim::push::install # Example: ./openim-push.sh openim::push::install
@@ -39,7 +39,7 @@
# export OPENIM_PUSH_PORT="9090 9091 9092" # export OPENIM_PUSH_PORT="9090 9091 9092"
# #
# Note: Ensure that the appropriate permissions and environmental variables are set prior to script execution. # Note: Ensure that the appropriate permissions and environmental variables are set prior to script execution.
# #
set -o errexit set -o errexit
set +o nounset set +o nounset
set -o pipefail set -o pipefail
@@ -50,30 +50,30 @@ OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
SERVER_NAME="openim-push" SERVER_NAME="openim-push"
function openim::push::start() { function openim::push::start() {
openim::log::status "Start OpenIM Push, binary root: ${SERVER_NAME}" openim::log::status "Start OpenIM Push, binary root: ${SERVER_NAME}"
openim::log::info "Start OpenIM Push, path: ${OPENIM_PUSH_BINARY}" openim::log::info "Start OpenIM Push, path: ${OPENIM_PUSH_BINARY}"
openim::log::status "prepare start push process, path: ${OPENIM_PUSH_BINARY}" openim::log::status "prepare start push process, path: ${OPENIM_PUSH_BINARY}"
openim::log::status "prepare start push process, port: ${OPENIM_PUSH_PORT}, prometheus port: ${PUSH_PROM_PORT}" openim::log::status "prepare start push process, port: ${OPENIM_PUSH_PORT}, prometheus port: ${PUSH_PROM_PORT}"
OPENIM_PUSH_PORTS_ARRAY=$(openim::util::list-to-string ${OPENIM_PUSH_PORT} ) OPENIM_PUSH_PORTS_ARRAY=$(openim::util::list-to-string ${OPENIM_PUSH_PORT} )
PUSH_PROM_PORTS_ARRAY=$(openim::util::list-to-string ${PUSH_PROM_PORT} ) PUSH_PROM_PORTS_ARRAY=$(openim::util::list-to-string ${PUSH_PROM_PORT} )
openim::util::stop_services_with_name ${SERVER_NAME} openim::util::stop_services_with_name ${SERVER_NAME}
openim::log::status "push port list: ${OPENIM_PUSH_PORTS_ARRAY[@]}" openim::log::status "push port list: ${OPENIM_PUSH_PORTS_ARRAY[@]}"
openim::log::status "prometheus port list: ${PUSH_PROM_PORTS_ARRAY[@]}" openim::log::status "prometheus port list: ${PUSH_PROM_PORTS_ARRAY[@]}"
if [ ${#OPENIM_PUSH_PORTS_ARRAY[@]} -ne ${#PUSH_PROM_PORTS_ARRAY[@]} ]; then if [ ${#OPENIM_PUSH_PORTS_ARRAY[@]} -ne ${#PUSH_PROM_PORTS_ARRAY[@]} ]; then
openim::log::error_exit "The length of the two port lists is different!" openim::log::error_exit "The length of the two port lists is different!"
fi fi
for (( i=0; i<${#OPENIM_PUSH_PORTS_ARRAY[@]}; i++ )); do for (( i=0; i<${#OPENIM_PUSH_PORTS_ARRAY[@]}; i++ )); do
openim::log::info "start push process, port: ${OPENIM_PUSH_PORTS_ARRAY[$i]}, prometheus port: ${PUSH_PROM_PORTS_ARRAY[$i]}" openim::log::info "start push process, port: ${OPENIM_PUSH_PORTS_ARRAY[$i]}, prometheus port: ${PUSH_PROM_PORTS_ARRAY[$i]}"
nohup ${OPENIM_PUSH_BINARY} --port ${OPENIM_PUSH_PORTS_ARRAY[$i]} -c ${OPENIM_PUSH_CONFIG} --prometheus_port ${PUSH_PROM_PORTS_ARRAY[$i]} >> ${LOG_FILE} 2>&1 & nohup ${OPENIM_PUSH_BINARY} --port ${OPENIM_PUSH_PORTS_ARRAY[$i]} -c ${OPENIM_PUSH_CONFIG} --prometheus_port ${PUSH_PROM_PORTS_ARRAY[$i]} >> ${LOG_FILE} 2>&1 &
done done
openim::util::check_process_names ${SERVER_NAME} openim::util::check_process_names ${SERVER_NAME}
} }
###################################### Linux Systemd ###################################### ###################################### Linux Systemd ######################################
@@ -89,27 +89,27 @@ EOF
# install openim-push # install openim-push
function openim::push::install() { function openim::push::install() {
pushd "${OPENIM_ROOT}" pushd "${OPENIM_ROOT}"
# 1. Build openim-push # 1. Build openim-push
make build BINS=${SERVER_NAME} make build BINS=${SERVER_NAME}
openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}" openim::common::sudo "cp -r ${OPENIM_OUTPUT_HOSTBIN}/${SERVER_NAME} ${OPENIM_INSTALL_DIR}/${SERVER_NAME}"
openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}" openim::log::status "${SERVER_NAME} binary: ${OPENIM_INSTALL_DIR}/${SERVER_NAME}/${SERVER_NAME}"
# 2. Generate and install the openim-push configuration file (config) # 2. Generate and install the openim-push configuration file (config)
openim::log::status "${SERVER_NAME} config file: ${OPENIM_CONFIG_DIR}/config.yaml" openim::log::status "${SERVER_NAME} config file: ${OPENIM_CONFIG_DIR}/config.yaml"
# 3. Create and install the ${SERVER_NAME} systemd unit file # 3. Create and install the ${SERVER_NAME} systemd unit file
echo ${LINUX_PASSWORD} | sudo -S bash -c \ echo ${LINUX_PASSWORD} | sudo -S bash -c \
"SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}" "SERVER_NAME=${SERVER_NAME} ./scripts/genconfig.sh ${ENV_FILE} deployments/templates/openim.service > ${SYSTEM_FILE_PATH}"
openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}" openim::log::status "${SERVER_NAME} systemd file: ${SYSTEM_FILE_PATH}"
# 4. Start the openim-push service # 4. Start the openim-push service
openim::common::sudo "systemctl daemon-reload" openim::common::sudo "systemctl daemon-reload"
openim::common::sudo "systemctl restart ${SERVER_NAME}" openim::common::sudo "systemctl restart ${SERVER_NAME}"
openim::common::sudo "systemctl enable ${SERVER_NAME}" openim::common::sudo "systemctl enable ${SERVER_NAME}"
openim::push::status || return 1 openim::push::status || return 1
openim::push::info openim::push::info
openim::log::info "install ${SERVER_NAME} successfully" openim::log::info "install ${SERVER_NAME} successfully"
popd popd
} }
@@ -133,7 +133,7 @@ function openim::push::status() {
openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly" openim::log::error "${SERVER_NAME} failed to start, maybe not installed properly"
return 1 return 1
} }
# The listening port is hardcode in the configuration file # The listening port is hardcode in the configuration file
if echo | telnet ${OPENIM_MSGGATEWAY_HOST} ${OPENIM_PUSH_PORT} 2>&1|grep refused &>/dev/null;then # Assuming a different port for push if echo | telnet ${OPENIM_MSGGATEWAY_HOST} ${OPENIM_PUSH_PORT} 2>&1|grep refused &>/dev/null;then # Assuming a different port for push
openim::log::error "cannot access health check port, ${SERVER_NAME} maybe not startup" openim::log::error "cannot access health check port, ${SERVER_NAME} maybe not startup"
+3 -3
View File
@@ -15,10 +15,10 @@
# limitations under the License. # limitations under the License.
# #
# OpenIM RPC Service Control Script # OpenIM RPC Service Control Script
# #
# Description: # Description:
# This script provides a control interface for the OpenIM RPC service within a Linux environment. It offers functionalities to start multiple RPC services, each denoted by their respective names under openim::rpc::service_name. # This script provides a control interface for the OpenIM RPC service within a Linux environment. It offers functionalities to start multiple RPC services, each denoted by their respective names under openim::rpc::service_name.
# #
# Features: # Features:
# 1. Robust error handling using Bash built-ins like 'errexit', 'nounset', and 'pipefail'. # 1. Robust error handling using Bash built-ins like 'errexit', 'nounset', and 'pipefail'.
# 2. The capability to source common utility functions and configurations to ensure uniform environmental settings. # 2. The capability to source common utility functions and configurations to ensure uniform environmental settings.
@@ -125,7 +125,7 @@ function openim::rpc::start() {
openim::util::stop_services_on_ports ${OPENIM_RPC_PORT_LISTARIES[$i]} openim::util::stop_services_on_ports ${OPENIM_RPC_PORT_LISTARIES[$i]}
openim::log::info "OpenIM ${OPENIM_RPC_SERVICE_LISTARIES[$i]} config path: ${OPENIM_RPC_CONFIG}" openim::log::info "OpenIM ${OPENIM_RPC_SERVICE_LISTARIES[$i]} config path: ${OPENIM_RPC_CONFIG}"
# Get the service and Prometheus ports. # Get the service and Prometheus ports.
OPENIM_RPC_SERVICE_PORTS=( $(openim::util::list-to-string ${OPENIM_RPC_PORT_LISTARIES[$i]}) ) OPENIM_RPC_SERVICE_PORTS=( $(openim::util::list-to-string ${OPENIM_RPC_PORT_LISTARIES[$i]}) )
read -a OPENIM_RPC_SERVICE_PORTS_ARRAY <<< ${OPENIM_RPC_SERVICE_PORTS} read -a OPENIM_RPC_SERVICE_PORTS_ARRAY <<< ${OPENIM_RPC_SERVICE_PORTS}
+2 -2
View File
@@ -18,9 +18,9 @@
# #
# Description: # Description:
# This script is responsible for managing the lifecycle of OpenIM tools, which include starting, stopping, # This script is responsible for managing the lifecycle of OpenIM tools, which include starting, stopping,
# and handling pre and post operations. It's designed to be modular and extensible, ensuring that the # and handling pre and post operations. It's designed to be modular and extensible, ensuring that the
# individual operations can be managed separately, and integrated seamlessly with Linux systemd. # individual operations can be managed separately, and integrated seamlessly with Linux systemd.
# #
# Features: # Features:
# 1. Robust error handling using Bash built-ins like 'errexit', 'nounset', and 'pipefail'. # 1. Robust error handling using Bash built-ins like 'errexit', 'nounset', and 'pipefail'.
# 2. The capability to source common utility functions and configurations to ensure uniform environmental settings. # 2. The capability to source common utility functions and configurations to ensure uniform environmental settings.
+582 -629
View File
File diff suppressed because it is too large Load Diff
+20 -20
View File
@@ -30,12 +30,12 @@ openim::chat::validate() {
openim::log::info "You can use 'scripts/install-chat.sh' to install a copy in third_party/." openim::log::info "You can use 'scripts/install-chat.sh' to install a copy in third_party/."
exit 1 exit 1
} }
# validate chat port is free # validate chat port is free
local port_check_command local port_check_command
if command -v ss &> /dev/null && ss -Version | grep 'iproute2' &> /dev/null; then if command -v ss &> /dev/null && ss -Version | grep 'iproute2' &> /dev/null; then
port_check_command="ss" port_check_command="ss"
elif command -v netstat &>/dev/null; then elif command -v netstat &>/dev/null; then
port_check_command="netstat" port_check_command="netstat"
else else
openim::log::usage "unable to identify if chat is bound to port ${CHAT_PORT}. unable to find ss or netstat utilities." openim::log::usage "unable to identify if chat is bound to port ${CHAT_PORT}. unable to find ss or netstat utilities."
@@ -46,24 +46,24 @@ openim::chat::validate() {
openim::log::usage "$(${port_check_command} -nat | grep "LISTEN" | grep "[\.:]${CHAT_PORT:?}")" openim::log::usage "$(${port_check_command} -nat | grep "LISTEN" | grep "[\.:]${CHAT_PORT:?}")"
exit 1 exit 1
fi fi
# need set the env of "CHAT_UNSUPPORTED_ARCH" on unstable arch. # need set the env of "CHAT_UNSUPPORTED_ARCH" on unstable arch.
arch=$(uname -m) arch=$(uname -m)
if [[ $arch =~ arm* ]]; then if [[ $arch =~ arm* ]]; then
export CHAT_UNSUPPORTED_ARCH=arm export CHAT_UNSUPPORTED_ARCH=arm
fi fi
# validate installed version is at least equal to minimum # validate installed version is at least equal to minimum
version=$(chat --version | grep Version | head -n 1 | cut -d " " -f 3) version=$(chat --version | grep Version | head -n 1 | cut -d " " -f 3)
if [[ $(openim::chat::version "${CHAT_VERSION}") -gt $(openim::chat::version "${version}") ]]; then if [[ $(openim::chat::version "${CHAT_VERSION}") -gt $(openim::chat::version "${version}") ]]; then
export PATH="${OPENIM_ROOT}"/third_party/chat:${PATH} export PATH="${OPENIM_ROOT}"/third_party/chat:${PATH}
hash chat hash chat
echo "${PATH}" echo "${PATH}"
version=$(chat --version | grep Version | head -n 1 | cut -d " " -f 3) version=$(chat --version | grep Version | head -n 1 | cut -d " " -f 3)
if [[ $(openim::chat::version "${CHAT_VERSION}") -gt $(openim::chat::version "${version}") ]]; then if [[ $(openim::chat::version "${CHAT_VERSION}") -gt $(openim::chat::version "${version}") ]]; then
openim::log::usage "chat version ${CHAT_VERSION} or greater required." openim::log::usage "chat version ${CHAT_VERSION} or greater required."
openim::log::info "You can use 'scripts/install-chat.sh' to install a copy in third_party/." openim::log::info "You can use 'scripts/install-chat.sh' to install a copy in third_party/."
exit 1 exit 1
fi fi
fi fi
} }
@@ -74,7 +74,7 @@ openim::chat::version() {
openim::chat::start() { openim::chat::start() {
# validate before running # validate before running
openim::chat::validate openim::chat::validate
# Start chat # Start chat
CHAT_DIR=${CHAT_DIR:-$(mktemp -d 2>/dev/null || mktemp -d -t test-chat.XXXXXX)} CHAT_DIR=${CHAT_DIR:-$(mktemp -d 2>/dev/null || mktemp -d -t test-chat.XXXXXX)}
if [[ -d "${ARTIFACTS:-}" ]]; then if [[ -d "${ARTIFACTS:-}" ]]; then
@@ -85,7 +85,7 @@ openim::chat::start() {
openim::log::info "chat --advertise-client-urls ${OPENIM_INTEGRATION_CHAT_URL} --data-dir ${CHAT_DIR} --listen-client-urls http://${CHAT_HOST}:${CHAT_PORT} --log-level=${CHAT_LOGLEVEL} 2> \"${CHAT_LOGFILE}\" >/dev/null" openim::log::info "chat --advertise-client-urls ${OPENIM_INTEGRATION_CHAT_URL} --data-dir ${CHAT_DIR} --listen-client-urls http://${CHAT_HOST}:${CHAT_PORT} --log-level=${CHAT_LOGLEVEL} 2> \"${CHAT_LOGFILE}\" >/dev/null"
chat --advertise-client-urls "${OPENIM_INTEGRATION_CHAT_URL}" --data-dir "${CHAT_DIR}" --listen-client-urls "${OPENIM_INTEGRATION_CHAT_URL}" --log-level="${CHAT_LOGLEVEL}" 2> "${CHAT_LOGFILE}" >/dev/null & chat --advertise-client-urls "${OPENIM_INTEGRATION_CHAT_URL}" --data-dir "${CHAT_DIR}" --listen-client-urls "${OPENIM_INTEGRATION_CHAT_URL}" --log-level="${CHAT_LOGLEVEL}" 2> "${CHAT_LOGFILE}" >/dev/null &
CHAT_PID=$! CHAT_PID=$!
echo "Waiting for chat to come up." echo "Waiting for chat to come up."
openim::util::wait_for_url "${OPENIM_INTEGRATION_CHAT_URL}/health" "chat: " 0.25 80 openim::util::wait_for_url "${OPENIM_INTEGRATION_CHAT_URL}/health" "chat: " 0.25 80
curl -fs -X POST "${OPENIM_INTEGRATION_CHAT_URL}/v3/kv/put" -d '{"key": "X3Rlc3Q=", "value": ""}' curl -fs -X POST "${OPENIM_INTEGRATION_CHAT_URL}/v3/kv/put" -d '{"key": "X3Rlc3Q=", "value": ""}'
@@ -108,7 +108,7 @@ openim::chat::start_scraping() {
} }
openim::chat::scrape() { openim::chat::scrape() {
curl -s -S "${OPENIM_INTEGRATION_CHAT_URL}/metrics" > "${CHAT_SCRAPE_DIR}/next" && mv "${CHAT_SCRAPE_DIR}/next" "${CHAT_SCRAPE_DIR}/$(date +%s).scrape" curl -s -S "${OPENIM_INTEGRATION_CHAT_URL}/metrics" > "${CHAT_SCRAPE_DIR}/next" && mv "${CHAT_SCRAPE_DIR}/next" "${CHAT_SCRAPE_DIR}/$(date +%s).scrape"
} }
openim::chat::stop() { openim::chat::stop() {
@@ -144,17 +144,17 @@ openim::chat::install() {
( (
local os local os
local arch local arch
os=$(openim::util::host_os) os=$(openim::util::host_os)
arch=$(openim::util::host_arch) arch=$(openim::util::host_arch)
cd "${OPENIM_ROOT}/third_party" || return 1 cd "${OPENIM_ROOT}/third_party" || return 1
if [[ $(readlink chat) == chat-v${CHAT_VERSION}-${os}-* ]]; then if [[ $(readlink chat) == chat-v${CHAT_VERSION}-${os}-* ]]; then
openim::log::info "chat v${CHAT_VERSION} already installed. To use:" openim::log::info "chat v${CHAT_VERSION} already installed. To use:"
openim::log::info "export PATH=\"$(pwd)/chat:\${PATH}\"" openim::log::info "export PATH=\"$(pwd)/chat:\${PATH}\""
return #already installed return #already installed
fi fi
if [[ ${os} == "darwin" ]]; then if [[ ${os} == "darwin" ]]; then
download_file="chat-v${CHAT_VERSION}-${os}-${arch}.zip" download_file="chat-v${CHAT_VERSION}-${os}-${arch}.zip"
url="https://github.com/chat-io/chat/releases/download/v${CHAT_VERSION}/${download_file}" url="https://github.com/chat-io/chat/releases/download/v${CHAT_VERSION}/${download_file}"
@@ -162,7 +162,7 @@ openim::chat::install() {
unzip -o "${download_file}" unzip -o "${download_file}"
ln -fns "chat-v${CHAT_VERSION}-${os}-${arch}" chat ln -fns "chat-v${CHAT_VERSION}-${os}-${arch}" chat
rm "${download_file}" rm "${download_file}"
elif [[ ${os} == "linux" ]]; then elif [[ ${os} == "linux" ]]; then
url="https://github.com/coreos/chat/releases/download/v${CHAT_VERSION}/chat-v${CHAT_VERSION}-${os}-${arch}.tar.gz" url="https://github.com/coreos/chat/releases/download/v${CHAT_VERSION}/chat-v${CHAT_VERSION}-${os}-${arch}.tar.gz"
download_file="chat-v${CHAT_VERSION}-${os}-${arch}.tar.gz" download_file="chat-v${CHAT_VERSION}-${os}-${arch}.tar.gz"
openim::util::download_file "${url}" "${download_file}" openim::util::download_file "${url}" "${download_file}"
+56 -56
View File
@@ -21,24 +21,24 @@
# shellcheck disable=SC2034 # shellcheck disable=SC2034
if [ -z "${COLOR_OPEN+x}" ]; then if [ -z "${COLOR_OPEN+x}" ]; then
COLOR_OPEN=1 COLOR_OPEN=1
fi fi
# Function for colored echo # Function for colored echo
openim::color::echo() { openim::color::echo() {
COLOR=$1 COLOR=$1
[ $COLOR_OPEN -eq 1 ] && echo -e "${COLOR} $(date '+%Y-%m-%d %H:%M:%S') $@ ${COLOR_SUFFIX}" [ $COLOR_OPEN -eq 1 ] && echo -e "${COLOR} $(date '+%Y-%m-%d %H:%M:%S') $@ ${COLOR_SUFFIX}"
shift shift
} }
# Define color variables # Define color variables
# --- Feature --- # --- Feature ---
COLOR_NORMAL='\033[0m';COLOR_BOLD='\033[1m';COLOR_DIM='\033[2m';COLOR_UNDER='\033[4m'; COLOR_NORMAL='\033[0m';COLOR_BOLD='\033[1m';COLOR_DIM='\033[2m';COLOR_UNDER='\033[4m';
COLOR_ITALIC='\033[3m';COLOR_NOITALIC='\033[23m';COLOR_BLINK='\033[5m'; COLOR_ITALIC='\033[3m';COLOR_NOITALIC='\033[23m';COLOR_BLINK='\033[5m';
COLOR_REVERSE='\033[7m';COLOR_CONCEAL='\033[8m';COLOR_NOBOLD='\033[22m'; COLOR_REVERSE='\033[7m';COLOR_CONCEAL='\033[8m';COLOR_NOBOLD='\033[22m';
COLOR_NOUNDER='\033[24m';COLOR_NOBLINK='\033[25m'; COLOR_NOUNDER='\033[24m';COLOR_NOBLINK='\033[25m';
# --- Front color --- # --- Front color ---
COLOR_BLACK='\033[30m'; COLOR_BLACK='\033[30m';
COLOR_RED='\033[31m'; COLOR_RED='\033[31m';
COLOR_GREEN='\033[32m'; COLOR_GREEN='\033[32m';
@@ -48,13 +48,13 @@ COLOR_MAGENTA='\033[35m';
COLOR_CYAN='\033[36m'; COLOR_CYAN='\033[36m';
COLOR_WHITE='\033[37m'; COLOR_WHITE='\033[37m';
# --- background color --- # --- background color ---
COLOR_BBLACK='\033[40m';COLOR_BRED='\033[41m'; COLOR_BBLACK='\033[40m';COLOR_BRED='\033[41m';
COLOR_BGREEN='\033[42m';COLOR_BYELLOW='\033[43m'; COLOR_BGREEN='\033[42m';COLOR_BYELLOW='\033[43m';
COLOR_BBLUE='\033[44m';COLOR_BMAGENTA='\033[45m'; COLOR_BBLUE='\033[44m';COLOR_BMAGENTA='\033[45m';
COLOR_BCYAN='\033[46m';COLOR_BWHITE='\033[47m'; COLOR_BCYAN='\033[46m';COLOR_BWHITE='\033[47m';
# --- Color definitions --- # --- Color definitions ---
# Color definitions # Color definitions
COLOR_SUFFIX="\033[0m" # End all colors and special effects COLOR_SUFFIX="\033[0m" # End all colors and special effects
BLACK_PREFIX="\033[30m" # Black prefix BLACK_PREFIX="\033[30m" # Black prefix
@@ -86,54 +86,54 @@ openim::color::print_color() {
# test functions # test functions
openim::color::test() { openim::color::test() {
echo "Starting the color tests..." echo "Starting the color tests..."
echo "Testing normal echo without color" echo "Testing normal echo without color"
openim::color::echo $COLOR_NORMAL "This is a normal text" openim::color::echo $COLOR_NORMAL "This is a normal text"
echo "Testing bold echo" echo "Testing bold echo"
openim::color::echo $COLOR_BOLD "This is bold text" openim::color::echo $COLOR_BOLD "This is bold text"
echo "Testing dim echo" echo "Testing dim echo"
openim::color::echo $COLOR_DIM "This is dim text" openim::color::echo $COLOR_DIM "This is dim text"
echo "Testing underlined echo" echo "Testing underlined echo"
openim::color::echo $COLOR_UNDER "This is underlined text" openim::color::echo $COLOR_UNDER "This is underlined text"
echo "Testing italic echo" echo "Testing italic echo"
openim::color::echo $COLOR_ITALIC "This is italic text" openim::color::echo $COLOR_ITALIC "This is italic text"
echo "Testing red color" echo "Testing red color"
openim::color::echo $COLOR_RED "This is red text" openim::color::echo $COLOR_RED "This is red text"
echo "Testing green color" echo "Testing green color"
openim::color::echo $COLOR_GREEN "This is green text" openim::color::echo $COLOR_GREEN "This is green text"
echo "Testing yellow color" echo "Testing yellow color"
openim::color::echo $COLOR_YELLOW "This is yellow text" openim::color::echo $COLOR_YELLOW "This is yellow text"
echo "Testing blue color" echo "Testing blue color"
openim::color::echo $COLOR_BLUE "This is blue text" openim::color::echo $COLOR_BLUE "This is blue text"
echo "Testing magenta color" echo "Testing magenta color"
openim::color::echo $COLOR_MAGENTA "This is magenta text" openim::color::echo $COLOR_MAGENTA "This is magenta text"
echo "Testing cyan color" echo "Testing cyan color"
openim::color::echo $COLOR_CYAN "This is cyan text" openim::color::echo $COLOR_CYAN "This is cyan text"
echo "Testing black background" echo "Testing black background"
openim::color::echo $COLOR_BBLACK "This is text with black background" openim::color::echo $COLOR_BBLACK "This is text with black background"
echo "Testing red background" echo "Testing red background"
openim::color::echo $COLOR_BRED "This is text with red background" openim::color::echo $COLOR_BRED "This is text with red background"
echo "Testing green background" echo "Testing green background"
openim::color::echo $COLOR_BGREEN "This is text with green background" openim::color::echo $COLOR_BGREEN "This is text with green background"
echo "Testing blue background" echo "Testing blue background"
openim::color::echo $COLOR_BBLUE "This is text with blue background" openim::color::echo $COLOR_BBLUE "This is text with blue background"
echo "All tests completed!" echo "All tests completed!"
} }
# openim::color::test # openim::color::test
+27 -27
View File
@@ -21,24 +21,24 @@ ENABLE_LOGGING="${ENABLE_LOGGING:-true}"
# If OPENIM_OUTPUT is not set, set it to the default value # If OPENIM_OUTPUT is not set, set it to the default value
if [ -z "${OPENIM_OUTPUT+x}" ]; then if [ -z "${OPENIM_OUTPUT+x}" ]; then
OPENIM_OUTPUT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../_output" && pwd -P)" OPENIM_OUTPUT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../_output" && pwd -P)"
fi fi
# Set the log file path # Set the log file path
LOG_FILE="${OPENIM_OUTPUT}/logs/openim_$(date '+%Y%m%d').log" LOG_FILE="${OPENIM_OUTPUT}/logs/openim_$(date '+%Y%m%d').log"
if [[ ! -d "${OPENIM_OUTPUT}/logs" ]]; then if [[ ! -d "${OPENIM_OUTPUT}/logs" ]]; then
mkdir -p "${OPENIM_OUTPUT}/logs" mkdir -p "${OPENIM_OUTPUT}/logs"
touch "$LOG_FILE" touch "$LOG_FILE"
fi fi
# Define the logging function # Define the logging function
function echo_log() { function echo_log() {
if $ENABLE_LOGGING; then if $ENABLE_LOGGING; then
echo -e "$@" | tee -a "${LOG_FILE}" echo -e "$@" | tee -a "${LOG_FILE}"
else else
echo -e "$@" echo -e "$@"
fi fi
} }
# MAX_LOG_SIZE=10485760 # 10MB # MAX_LOG_SIZE=10485760 # 10MB
@@ -50,11 +50,11 @@ function echo_log() {
# Borrowed from https://gist.github.com/ahendrix/7030300 # Borrowed from https://gist.github.com/ahendrix/7030300
openim::log::errexit() { openim::log::errexit() {
local err="${PIPESTATUS[*]}" local err="${PIPESTATUS[*]}"
# If the shell we are in doesn't have errexit set (common in subshells) then # If the shell we are in doesn't have errexit set (common in subshells) then
# don't dump stacks. # don't dump stacks.
set +o | grep -qe "-o errexit" || return set +o | grep -qe "-o errexit" || return
set +o xtrace set +o xtrace
local code="${1:-1}" local code="${1:-1}"
# Print out the stack trace described by $function_stack # Print out the stack trace described by $function_stack
@@ -73,7 +73,7 @@ openim::log::install_errexit() {
# trap ERR to provide an error handler whenever a command exits nonzero this # trap ERR to provide an error handler whenever a command exits nonzero this
# is a more verbose version of set -o errexit # is a more verbose version of set -o errexit
trap 'openim::log::errexit' ERR trap 'openim::log::errexit' ERR
# setting errtrace allows our ERR trap handler to be propagated to functions, # setting errtrace allows our ERR trap handler to be propagated to functions,
# expansions and subshells # expansions and subshells
set -o errtrace set -o errtrace
@@ -110,7 +110,7 @@ openim::log::error_exit() {
local code="${2:-1}" local code="${2:-1}"
local stack_skip="${3:-0}" local stack_skip="${3:-0}"
stack_skip=$((stack_skip + 1)) stack_skip=$((stack_skip + 1))
if [[ ${OPENIM_VERBOSE} -ge 4 ]]; then if [[ ${OPENIM_VERBOSE} -ge 4 ]]; then
local source_file=${BASH_SOURCE[${stack_skip}]} local source_file=${BASH_SOURCE[${stack_skip}]}
local source_line=${BASH_LINENO[$((stack_skip - 1))]} local source_line=${BASH_LINENO[$((stack_skip - 1))]}
@@ -118,12 +118,12 @@ openim::log::error_exit() {
[[ -z ${1-} ]] || { [[ -z ${1-} ]] || {
echo_log " ${1}" >&2 echo_log " ${1}" >&2
} }
openim::log::stack ${stack_skip} openim::log::stack ${stack_skip}
echo_log "Exiting with status ${code}" >&2 echo_log "Exiting with status ${code}" >&2
fi fi
exit "${code}" exit "${code}"
} }
@@ -152,7 +152,7 @@ openim::log::usage_from_stdin() {
while read -r line; do while read -r line; do
messages+=("${line}") messages+=("${line}")
done done
openim::log::usage "${messages[@]}" openim::log::usage "${messages[@]}"
} }
@@ -162,7 +162,7 @@ openim::log::info() {
if [[ ${OPENIM_VERBOSE} < ${V} ]]; then if [[ ${OPENIM_VERBOSE} < ${V} ]]; then
return return
fi fi
for message; do for message; do
echo_log "${message}" echo_log "${message}"
done done
@@ -181,7 +181,7 @@ openim::log::info_from_stdin() {
while read -r line; do while read -r line; do
messages+=("${line}") messages+=("${line}")
done done
openim::log::info "${messages[@]}" openim::log::info "${messages[@]}"
} }
@@ -191,7 +191,7 @@ openim::log::status() {
if [[ ${OPENIM_VERBOSE} < ${V} ]]; then if [[ ${OPENIM_VERBOSE} < ${V} ]]; then
return return
fi fi
timestamp=$(date +"[%m%d %H:%M:%S]") timestamp=$(date +"[%m%d %H:%M:%S]")
echo_log "+++ ${timestamp} ${1}" echo_log "+++ ${timestamp} ${1}"
shift shift
@@ -203,20 +203,20 @@ openim::log::status() {
openim::log::success() { openim::log::success() {
local V="${V:-0}" local V="${V:-0}"
if [[ ${OPENIM_VERBOSE} < ${V} ]]; then if [[ ${OPENIM_VERBOSE} < ${V} ]]; then
return return
fi fi
timestamp=$(date +"%m%d %H:%M:%S") timestamp=$(date +"%m%d %H:%M:%S")
echo_log -e "${COLOR_GREEN}[success ${timestamp}] ${COLOR_SUFFIX}==> " "$@" echo_log -e "${COLOR_GREEN}[success ${timestamp}] ${COLOR_SUFFIX}==> " "$@"
} }
function openim::log::test_log() { function openim::log::test_log() {
echo_log "test log" echo_log "test log"
openim::log::info "openim::log::info" openim::log::info "openim::log::info"
openim::log::progress "openim::log::progress" openim::log::progress "openim::log::progress"
openim::log::status "openim::log::status" openim::log::status "openim::log::status"
openim::log::success "openim::log::success" openim::log::success "openim::log::success"
openim::log::error "openim::log::error" openim::log::error "openim::log::error"
openim::log::error_exit "openim::log::error_exit" openim::log::error_exit "openim::log::error_exit"
} }
# openim::log::test_log # openim::log::test_log
+26 -29
View File
@@ -25,7 +25,6 @@
readonly BUCKET="openim-1306374445" readonly BUCKET="openim-1306374445"
readonly REGION="ap-guangzhou" readonly REGION="ap-guangzhou"
readonly COS_RELEASE_DIR="openim-release" readonly COS_RELEASE_DIR="openim-release"
# readonly COS_RELEASE_DIR="openim-advanced-release" # !pro
# default cos command tool coscli or coscmd # default cos command tool coscli or coscmd
readonly COSTOOL="coscli" readonly COSTOOL="coscli"
@@ -38,22 +37,20 @@ readonly RELEASE_IMAGES="${LOCAL_OUTPUT_ROOT}/release-images"
# OpenIM github account info # OpenIM github account info
readonly OPENIM_GITHUB_ORG=openimsdk readonly OPENIM_GITHUB_ORG=openimsdk
readonly OPENIM_GITHUB_REPO=open-im-server readonly OPENIM_GITHUB_REPO=open-im-server
# readonly OPENIM_GITHUB_REPO=open-im-server-enterprise # !pro readonly CHAT_GITHUB_REPO=chat
readonly ARTIFACT=openim.tar.gz readonly ARTIFACT=openim.tar.gz
# readonly ARTIFACT=openim-enterprise.tar.gz # !pro
readonly CHECKSUM=${ARTIFACT}.sha1sum readonly CHECKSUM=${ARTIFACT}.sha1sum
OPENIM_BUILD_CONFORMANCE=${OPENIM_BUILD_CONFORMANCE:-y} OPENIM_BUILD_CONFORMANCE=${OPENIM_BUILD_CONFORMANCE:-y}
OPENIM_BUILD_PULL_LATEST_IMAGES=${OPENIM_BUILD_PULL_LATEST_IMAGES:-y} OPENIM_BUILD_PULL_LATEST_IMAGES=${OPENIM_BUILD_PULL_LATEST_IMAGES:-y}
if [ -z "${OPENIM_ROOT}" ]; then if [ -z "${OPENIM_ROOT}" ]; then
OPENIM_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" OPENIM_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
fi fi
if [ -z "${TOOLS_DIR}" ]; then if [ -z "${TOOLS_DIR}" ]; then
TOOLS_DIR="${OPENIM_ROOT}/_output/tools" TOOLS_DIR="${OPENIM_ROOT}/_output/tools"
fi fi
# Validate a ci version # Validate a ci version
@@ -80,10 +77,10 @@ function openim::release::parse_and_validate_ci_version() {
openim::log::error "Invalid ci version: '${version}', must match regex ${version_regex}" openim::log::error "Invalid ci version: '${version}', must match regex ${version_regex}"
return 1 return 1
} }
# The VERSION variables are used when this file is sourced, hence # The VERSION variables are used when this file is sourced, hence
# the shellcheck SC2034 'appears unused' warning is to be ignored. # the shellcheck SC2034 'appears unused' warning is to be ignored.
# shellcheck disable=SC2034 # shellcheck disable=SC2034
VERSION_MAJOR="${BASH_REMATCH[1]}" VERSION_MAJOR="${BASH_REMATCH[1]}"
# shellcheck disable=SC2034 # shellcheck disable=SC2034
@@ -118,7 +115,7 @@ function openim::release::package_tarballs() {
openim::release::package_openim_manifests_tarball & openim::release::package_openim_manifests_tarball &
openim::release::package_server_tarballs & openim::release::package_server_tarballs &
openim::util::wait-for-jobs || { openim::log::error "previous tarball phase failed"; return 1; } openim::util::wait-for-jobs || { openim::log::error "previous tarball phase failed"; return 1; }
openim::release::package_final_tarball & # _final depends on some of the previous phases openim::release::package_final_tarball & # _final depends on some of the previous phases
openim::util::wait-for-jobs || { openim::log::error "previous tarball phase failed"; return 1; } openim::util::wait-for-jobs || { openim::log::error "previous tarball phase failed"; return 1; }
} }
@@ -146,24 +143,24 @@ function openim::release::package_src_tarball() {
git archive -o "${src_tarball}" HEAD git archive -o "${src_tarball}" HEAD
else else
find "${OPENIM_ROOT}" -mindepth 1 -maxdepth 1 \ find "${OPENIM_ROOT}" -mindepth 1 -maxdepth 1 \
! \( \ ! \( \
\( -path "${OPENIM_ROOT}"/_\* -o \ \( -path "${OPENIM_ROOT}"/_\* -o \
-path "${OPENIM_ROOT}"/.git\* -o \ -path "${OPENIM_ROOT}"/.git\* -o \
-path "${OPENIM_ROOT}"/.github\* -o \ -path "${OPENIM_ROOT}"/.github\* -o \
-path "${OPENIM_ROOT}"/components\* -o \ -path "${OPENIM_ROOT}"/components\* -o \
-path "${OPENIM_ROOT}"/logs\* -o \ -path "${OPENIM_ROOT}"/logs\* -o \
-path "${OPENIM_ROOT}"/.gitignore\* -o \ -path "${OPENIM_ROOT}"/.gitignore\* -o \
-path "${OPENIM_ROOT}"/.gsemver.yml\* -o \ -path "${OPENIM_ROOT}"/.gsemver.yml\* -o \
-path "${OPENIM_ROOT}"/.config\* -o \ -path "${OPENIM_ROOT}"/.config\* -o \
-path "${OPENIM_ROOT}"/.chglog\* -o \ -path "${OPENIM_ROOT}"/.chglog\* -o \
-path "${OPENIM_ROOT}"/.gitlint -o \ -path "${OPENIM_ROOT}"/.gitlint -o \
-path "${OPENIM_ROOT}"/.golangci.yml -o \ -path "${OPENIM_ROOT}"/.golangci.yml -o \
-path "${OPENIM_ROOT}"/build/goreleaser.yaml -o \ -path "${OPENIM_ROOT}"/build/goreleaser.yaml -o \
-path "${OPENIM_ROOT}"/.note.md -o \ -path "${OPENIM_ROOT}"/.note.md -o \
-path "${OPENIM_ROOT}"/.todo.md \ -path "${OPENIM_ROOT}"/.todo.md \
\) -prune \ \) -prune \
\) -print0 \ \) -print0 \
| "${TAR}" czf "${src_tarball}" --transform "s|${OPENIM_ROOT#/*}|openim|" --null -T - | "${TAR}" czf "${src_tarball}" --transform "s|${OPENIM_ROOT#/*}|openim|" --null -T -
fi fi
} }
@@ -171,7 +168,7 @@ function openim::release::package_src_tarball() {
function openim::release::package_server_tarballs() { function openim::release::package_server_tarballs() {
# Find all of the built client binaries # Find all of the built client binaries
local long_platforms=("${LOCAL_OUTPUT_BINPATH}"/*/*) local long_platforms=("${LOCAL_OUTPUT_BINPATH}"/*/*)
if [[ -n ${OPENIM_BUILD_PLATFORMS-} ]]; then if [[ -n ${OPENIM_BUILD_PLATFORMS-} ]]; then
read -ra long_platforms <<< "${OPENIM_BUILD_PLATFORMS}" read -ra long_platforms <<< "${OPENIM_BUILD_PLATFORMS}"
fi fi
@@ -639,7 +636,7 @@ function openim::release::github_release() {
for file in ${RELEASE_TARS}/*.tar.gz; do for file in ${RELEASE_TARS}/*.tar.gz; do
if [[ -f "$file" ]]; then if [[ -f "$file" ]]; then
filename=$(basename "$file") filename=$(basename "$file")
openim::log::info "Update file ${filename} to release vertion ${OPENIM_GIT_VERSION}" openim::log::info "Update file ${filename} to release vertion ${OPENIM_GIT_VERSION}"
${TOOLS_DIR}/github-release upload \ ${TOOLS_DIR}/github-release upload \
--user ${OPENIM_GITHUB_ORG} \ --user ${OPENIM_GITHUB_ORG} \
--repo ${OPENIM_GITHUB_REPO} \ --repo ${OPENIM_GITHUB_REPO} \
+240 -240
View File
@@ -30,27 +30,27 @@ function openim:util::setup_ssh_key_copy() {
local hosts_file="$1" local hosts_file="$1"
local username="${2:-root}" local username="${2:-root}"
local password="${3:-123}" local password="${3:-123}"
local sshkey_file=~/.ssh/id_rsa.pub local sshkey_file=~/.ssh/id_rsa.pub
# check sshkey file # check sshkey file
if [[ ! -e $sshkey_file ]]; then if [[ ! -e $sshkey_file ]]; then
expect -c " expect -c "
spawn ssh-keygen -t rsa spawn ssh-keygen -t rsa
expect \"Enter*\" { send \"\n\"; exp_continue; } expect \"Enter*\" { send \"\n\"; exp_continue; }
" "
fi fi
# get hosts list # get hosts list
local hosts=$(awk '/^[^#]/ {print $1}' "${hosts_file}") local hosts=$(awk '/^[^#]/ {print $1}' "${hosts_file}")
ssh_key_copy() { ssh_key_copy() {
local target=$1 local target=$1
# delete history # delete history
sed -i "/$target/d" ~/.ssh/known_hosts sed -i "/$target/d" ~/.ssh/known_hosts
# copy key # copy key
expect -c " expect -c "
set timeout 100 set timeout 100
spawn ssh-copy-id $username@$target spawn ssh-copy-id $username@$target
@@ -62,14 +62,14 @@ function openim:util::setup_ssh_key_copy() {
expect eof expect eof
" "
} }
# auto sshkey pair # auto sshkey pair
for host in $hosts; do for host in $hosts; do
if ! ping -i 0.2 -c 3 -W 1 "$host" > /dev/null 2>&1; then if ! ping -i 0.2 -c 3 -W 1 "$host" > /dev/null 2>&1; then
echo "[ERROR]: Can't connect $host" echo "[ERROR]: Can't connect $host"
continue continue
fi fi
local host_entry=$(awk "/$host/"'{print $1, $2}' /etc/hosts) local host_entry=$(awk "/$host/"'{print $1, $2}' /etc/hosts)
if [[ $host_entry ]]; then if [[ $host_entry ]]; then
local hostaddr=$(echo "$host_entry" | awk '{print $1}') local hostaddr=$(echo "$host_entry" | awk '{print $1}')
@@ -102,7 +102,7 @@ openim::util::array_contains() {
for element; do for element; do
if [[ "${element}" == "${search}" ]]; then if [[ "${element}" == "${search}" ]]; then
return 0 return 0
fi fi
done done
return 1 return 1
} }
@@ -113,12 +113,12 @@ openim::util::wait_for_url() {
local wait=${3:-1} local wait=${3:-1}
local times=${4:-30} local times=${4:-30}
local maxtime=${5:-1} local maxtime=${5:-1}
command -v curl >/dev/null || { command -v curl >/dev/null || {
openim::log::usage "curl must be installed" openim::log::usage "curl must be installed"
exit 1 exit 1
} }
local i local i
for i in $(seq 1 "${times}"); do for i in $(seq 1 "${times}"); do
local out local out
@@ -156,20 +156,20 @@ openim::util::trap_add() {
local trap_add_cmd local trap_add_cmd
trap_add_cmd=$1 trap_add_cmd=$1
shift shift
for trap_add_name in "$@"; do for trap_add_name in "$@"; do
local existing_cmd local existing_cmd
local new_cmd local new_cmd
# Grab the currently defined trap commands for this trap # Grab the currently defined trap commands for this trap
existing_cmd=$(trap -p "${trap_add_name}" | awk -F"'" '{print $2}') existing_cmd=$(trap -p "${trap_add_name}" | awk -F"'" '{print $2}')
if [[ -z "${existing_cmd}" ]]; then if [[ -z "${existing_cmd}" ]]; then
new_cmd="${trap_add_cmd}" new_cmd="${trap_add_cmd}"
else else
new_cmd="${trap_add_cmd};${existing_cmd}" new_cmd="${trap_add_cmd};${existing_cmd}"
fi fi
# Assign the test. Disable the shellcheck warning telling that trap # Assign the test. Disable the shellcheck warning telling that trap
# commands should be single quoted to avoid evaluating them at this # commands should be single quoted to avoid evaluating them at this
# point instead evaluating them at run time. The logic of adding new # point instead evaluating them at run time. The logic of adding new
@@ -200,14 +200,14 @@ openim::util::host_os() {
case "$(uname -s)" in case "$(uname -s)" in
Darwin) Darwin)
host_os=darwin host_os=darwin
;; ;;
Linux) Linux)
host_os=linux host_os=linux
;; ;;
*) *)
openim::log::error "Unsupported host OS. Must be Linux or Mac OS X." openim::log::error "Unsupported host OS. Must be Linux or Mac OS X."
exit 1 exit 1
;; ;;
esac esac
echo "${host_os}" echo "${host_os}"
} }
@@ -217,70 +217,70 @@ openim::util::host_arch() {
case "$(uname -m)" in case "$(uname -m)" in
x86_64*) x86_64*)
host_arch=amd64 host_arch=amd64
;; ;;
i?86_64*) i?86_64*)
host_arch=amd64 host_arch=amd64
;; ;;
amd64*) amd64*)
host_arch=amd64 host_arch=amd64
;; ;;
aarch64*) aarch64*)
host_arch=arm64 host_arch=arm64
;; ;;
arm64*) arm64*)
host_arch=arm64 host_arch=arm64
;; ;;
arm*) arm*)
host_arch=arm host_arch=arm
;; ;;
i?86*) i?86*)
host_arch=x86 host_arch=x86
;; ;;
s390x*) s390x*)
host_arch=s390x host_arch=s390x
;; ;;
ppc64le*) ppc64le*)
host_arch=ppc64le host_arch=ppc64le
;; ;;
*) *)
openim::log::error "Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le." openim::log::error "Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le."
exit 1 exit 1
;; ;;
esac esac
echo "${host_arch}" echo "${host_arch}"
} }
# Define a bash function to check the versions of Docker and Docker Compose # Define a bash function to check the versions of Docker and Docker Compose
openim::util::check_docker_and_compose_versions() { openim::util::check_docker_and_compose_versions() {
# Define the required versions of Docker and Docker Compose # Define the required versions of Docker and Docker Compose
required_docker_version="20.10.0" required_docker_version="20.10.0"
required_compose_version="2.0" required_compose_version="2.0"
# Get the currently installed Docker version # Get the currently installed Docker version
installed_docker_version=$(docker --version | awk '{print $3}' | sed 's/,//') installed_docker_version=$(docker --version | awk '{print $3}' | sed 's/,//')
# Check if the installed Docker version matches the required version # Check if the installed Docker version matches the required version
if [[ "$installed_docker_version" < "$required_docker_version" ]]; then if [[ "$installed_docker_version" < "$required_docker_version" ]]; then
echo "Docker version mismatch. Installed: $installed_docker_version, Required: $required_docker_version" echo "Docker version mismatch. Installed: $installed_docker_version, Required: $required_docker_version"
return 1 return 1
fi fi
# Check if the docker compose sub-command is available # Check if the docker compose sub-command is available
if ! docker compose version &> /dev/null; then if ! docker compose version &> /dev/null; then
echo "Docker does not support the docker compose sub-command" echo "Docker does not support the docker compose sub-command"
echo "You need to upgrade Docker to the right version" echo "You need to upgrade Docker to the right version"
return 1 return 1
fi fi
# Get the currently installed Docker Compose version # Get the currently installed Docker Compose version
installed_compose_version=$(docker compose version --short) installed_compose_version=$(docker compose version --short)
# Check if the installed Docker Compose version matches the required version # Check if the installed Docker Compose version matches the required version
if [[ "$installed_compose_version" < "$required_compose_version" ]]; then if [[ "$installed_compose_version" < "$required_compose_version" ]]; then
echo "Docker Compose version mismatch. Installed: $installed_compose_version, Required: $required_compose_version" echo "Docker Compose version mismatch. Installed: $installed_compose_version, Required: $required_compose_version"
return 1 return 1
fi fi
} }
@@ -292,80 +292,80 @@ openim::util::check_docker_and_compose_versions() {
# openim::util::check_ports 8080 8081 8082 # openim::util::check_ports 8080 8081 8082
# The function returns a status of 1 if any of the processes is not running. # The function returns a status of 1 if any of the processes is not running.
openim::util::check_ports() { openim::util::check_ports() {
# An array to collect ports of processes that are not running. # An array to collect ports of processes that are not running.
local not_started=() local not_started=()
# An array to collect information about processes that are running. # An array to collect information about processes that are running.
local started=() local started=()
openim::log::info "Checking ports: $*" openim::log::info "Checking ports: $*"
# Iterate over each given port. # Iterate over each given port.
for port in "$@"; do for port in "$@"; do
# Initialize variables # Initialize variables
# Check the OS and use the appropriate command # Check the OS and use the appropriate command
if [[ "$OSTYPE" == "linux-gnu"* ]]; then if [[ "$OSTYPE" == "linux-gnu"* ]]; then
if command -v ss > /dev/null 2>&1; then if command -v ss > /dev/null 2>&1; then
info=$(ss -ltnp | grep ":$port" || true) info=$(ss -ltnp | grep ":$port" || true)
else else
info=$(netstat -ltnp | grep ":$port" || true) info=$(netstat -ltnp | grep ":$port" || true)
fi fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
# For macOS, use lsof
info=$(lsof -P -i:"$port" | grep "LISTEN" || true)
fi
# Check if any process is using the port
if [[ -z $info ]]; then
not_started+=($port)
else
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Extract relevant details for Linux: Process Name, PID, and FD.
details=$(echo $info | sed -n 's/.*users:(("\([^"]*\)",pid=\([^,]*\),fd=\([^)]*\))).*/\1 \2 \3/p')
command=$(echo $details | awk '{print $1}')
pid=$(echo $details | awk '{print $2}')
fd=$(echo $details | awk '{print $3}')
elif [[ "$OSTYPE" == "darwin"* ]]; then elif [[ "$OSTYPE" == "darwin"* ]]; then
# Handle extraction for macOS # For macOS, use lsof
pid=$(echo $info | awk '{print $2}' | cut -d'/' -f1) info=$(lsof -P -i:"$port" | grep "LISTEN" || true)
command=$(ps -p $pid -o comm= | xargs basename) fi
fd=$(echo $info | awk '{print $4}' | cut -d'/' -f1)
fi # Check if any process is using the port
if [[ -z $info ]]; then
# Get the start time of the process using the PID not_started+=($port)
if [[ -z $pid ]]; then else
start_time="N/A" if [[ "$OSTYPE" == "linux-gnu"* ]]; then
else # Extract relevant details for Linux: Process Name, PID, and FD.
start_time=$(ps -p $pid -o lstart=) details=$(echo $info | sed -n 's/.*users:(("\([^"]*\)",pid=\([^,]*\),fd=\([^)]*\))).*/\1 \2 \3/p')
fi command=$(echo $details | awk '{print $1}')
pid=$(echo $details | awk '{print $2}')
started+=("Port $port - Command: $command, PID: $pid, FD: $fd, Started: $start_time") fd=$(echo $details | awk '{print $3}')
elif [[ "$OSTYPE" == "darwin"* ]]; then
# Handle extraction for macOS
pid=$(echo $info | awk '{print $2}' | cut -d'/' -f1)
command=$(ps -p $pid -o comm= | xargs basename)
fd=$(echo $info | awk '{print $4}' | cut -d'/' -f1)
fi
# Get the start time of the process using the PID
if [[ -z $pid ]]; then
start_time="N/A"
else
start_time=$(ps -p $pid -o lstart=)
fi
started+=("Port $port - Command: $command, PID: $pid, FD: $fd, Started: $start_time")
fi
done
# Print information about ports whose processes are not running.
if [[ ${#not_started[@]} -ne 0 ]]; then
openim::log::info "\n### Not started ports:"
for port in "${not_started[@]}"; do
openim::log::error "Port $port is not started."
done
fi
# Print information about ports whose processes are running.
if [[ ${#started[@]} -ne 0 ]]; then
openim::log::info "\n### Started ports:"
for info in "${started[@]}"; do
openim::log::info "$info"
done
fi
# If any of the processes is not running, return a status of 1.
if [[ ${#not_started[@]} -ne 0 ]]; then
echo "++++ OpenIM Log >> cat ${LOG_FILE}"
return 1
else
openim::log::success "All specified processes are running."
return 0
fi fi
done
# Print information about ports whose processes are not running.
if [[ ${#not_started[@]} -ne 0 ]]; then
openim::log::info "\n### Not started ports:"
for port in "${not_started[@]}"; do
openim::log::error "Port $port is not started."
done
fi
# Print information about ports whose processes are running.
if [[ ${#started[@]} -ne 0 ]]; then
openim::log::info "\n### Started ports:"
for info in "${started[@]}"; do
openim::log::info "$info"
done
fi
# If any of the processes is not running, return a status of 1.
if [[ ${#not_started[@]} -ne 0 ]]; then
echo "++++ OpenIM Log >> cat ${LOG_FILE}"
return 1
else
openim::log::success "All specified processes are running."
return 0
fi
} }
# set +o errexit # set +o errexit
@@ -381,75 +381,75 @@ openim::util::check_ports() {
# openim::util::check_process_names nginx mysql redis # openim::util::check_process_names nginx mysql redis
# The function returns a status of 1 if any of the processes is not running. # The function returns a status of 1 if any of the processes is not running.
openim::util::check_process_names() { openim::util::check_process_names() {
# Function to get the port of a process # Function to get the port of a process
get_port() { get_port() {
local pid=$1 local pid=$1
if [[ "$OSTYPE" == "linux-gnu"* ]]; then if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux # Linux
ss -ltnp 2>/dev/null | grep $pid | awk '{print $4}' | cut -d ':' -f2 ss -ltnp 2>/dev/null | grep $pid | awk '{print $4}' | cut -d ':' -f2
elif [[ "$OSTYPE" == "darwin"* ]]; then elif [[ "$OSTYPE" == "darwin"* ]]; then
# macOS # macOS
lsof -nP -iTCP -sTCP:LISTEN -a -p $pid | awk 'NR>1 {print $9}' | sed 's/.*://' lsof -nP -iTCP -sTCP:LISTEN -a -p $pid | awk 'NR>1 {print $9}' | sed 's/.*://'
else else
echo "Unsupported OS" echo "Unsupported OS"
return 1 return 1
fi
}
# Arrays to collect details of processes
local not_started=()
local started=()
openim::log::info "Checking processes: $*"
# Iterate over each given process name
for process_name in "$@"; do
# Use `pgrep` to find process IDs related to the given process name
local pids=($(pgrep -f $process_name))
# Check if any process IDs were found
if [[ ${#pids[@]} -eq 0 ]]; then
not_started+=($process_name)
else
# If there are PIDs, loop through each one
for pid in "${pids[@]}"; do
local command=$(ps -p $pid -o cmd=)
local start_time=$(ps -p $pid -o lstart=)
local port=$(get_port $pid)
# Check if port information was found for the PID
if [[ -z $port ]]; then
port="N/A"
fi fi
}
# Arrays to collect details of processes
local not_started=()
local started=()
openim::log::info "Checking processes: $*"
# Iterate over each given process name
for process_name in "$@"; do
# Use `pgrep` to find process IDs related to the given process name
local pids=($(pgrep -f $process_name))
started+=("Process $process_name - Command: $command, PID: $pid, Port: $port, Start time: $start_time") # Check if any process IDs were found
done if [[ ${#pids[@]} -eq 0 ]]; then
not_started+=($process_name)
else
# If there are PIDs, loop through each one
for pid in "${pids[@]}"; do
local command=$(ps -p $pid -o cmd=)
local start_time=$(ps -p $pid -o lstart=)
local port=$(get_port $pid)
# Check if port information was found for the PID
if [[ -z $port ]]; then
port="N/A"
fi
started+=("Process $process_name - Command: $command, PID: $pid, Port: $port, Start time: $start_time")
done
fi
done
# Print information
if [[ ${#not_started[@]} -ne 0 ]]; then
openim::log::info "Not started processes:"
for process_name in "${not_started[@]}"; do
openim::log::error "Process $process_name is not started."
done
fi
if [[ ${#started[@]} -ne 0 ]]; then
echo
openim::log::info "Started processes:"
for info in "${started[@]}"; do
openim::log::info "$info"
done
fi
# Return status
if [[ ${#not_started[@]} -ne 0 ]]; then
echo "++++ OpenIM Log >> cat ${LOG_FILE}"
return 1
else
openim::log::success "All processes are running."
return 0
fi fi
done
# Print information
if [[ ${#not_started[@]} -ne 0 ]]; then
openim::log::info "Not started processes:"
for process_name in "${not_started[@]}"; do
openim::log::error "Process $process_name is not started."
done
fi
if [[ ${#started[@]} -ne 0 ]]; then
echo
openim::log::info "Started processes:"
for info in "${started[@]}"; do
openim::log::info "$info"
done
fi
# Return status
if [[ ${#not_started[@]} -ne 0 ]]; then
echo "++++ OpenIM Log >> cat ${LOG_FILE}"
return 1
else
openim::log::success "All processes are running."
return 0
fi
} }
# openim::util::check_process_names docker-pr # openim::util::check_process_names docker-pr
@@ -462,30 +462,30 @@ openim::util::check_process_names() {
# openim::util::stop_services_on_ports 8080 8081 8082 # openim::util::stop_services_on_ports 8080 8081 8082
# The function returns a status of 1 if any service couldn't be stopped. # The function returns a status of 1 if any service couldn't be stopped.
openim::util::stop_services_on_ports() { openim::util::stop_services_on_ports() {
# An array to collect ports of processes that couldn't be stopped. # An array to collect ports of processes that couldn't be stopped.
local not_stopped=() local not_stopped=()
# An array to collect information about processes that were stopped. # An array to collect information about processes that were stopped.
local stopped=() local stopped=()
openim::log::info "Stopping services on ports: $*" openim::log::info "Stopping services on ports: $*"
# Iterate over each given port. # Iterate over each given port.
for port in "$@"; do for port in "$@"; do
# Use the `lsof` command to find process information related to the given port. # Use the `lsof` command to find process information related to the given port.
info=$(lsof -i :$port -n -P | grep LISTEN || true) info=$(lsof -i :$port -n -P | grep LISTEN || true)
# If there's process information, it means the process associated with the port is running. # If there's process information, it means the process associated with the port is running.
if [[ -n $info ]]; then if [[ -n $info ]]; then
# Extract the Process ID. # Extract the Process ID.
while read -r line; do while read -r line; do
local pid=$(echo $line | awk '{print $2}') local pid=$(echo $line | awk '{print $2}')
# Try to stop the service by killing its process. # Try to stop the service by killing its process.
if kill -TERM $pid; then if kill -TERM $pid; then
stopped+=($port) stopped+=($port)
else else
not_stopped+=($port) not_stopped+=($port)
fi fi
done <<< "$info" done <<< "$info"
fi fi
done done
@@ -519,7 +519,7 @@ openim::util::stop_services_on_ports() {
# nc -l -p 12345 # nc -l -p 12345
# nc -l -p 123456 # nc -l -p 123456
# ps -ef | grep "nc -l" # ps -ef | grep "nc -l"
# openim::util::stop_services_on_ports 1234 12345 # openim::util::stop_services_on_ports 1234 12345
# The `openim::util::stop_services_with_name` function stops services with specified names. # The `openim::util::stop_services_with_name` function stops services with specified names.
@@ -1086,7 +1086,7 @@ function openim::util::ensure-install-nginx {
exit 1 exit 1
fi fi
for port in "80" for port in 80
do do
if echo |telnet 127.0.0.1 $port 2>&1|grep refused &>/dev/null;then if echo |telnet 127.0.0.1 $port 2>&1|grep refused &>/dev/null;then
exit 1 exit 1
@@ -1263,7 +1263,7 @@ function openim:util::setup_ssh_key_copy() {
local sshkey_file=~/.ssh/id_rsa.pub local sshkey_file=~/.ssh/id_rsa.pub
# check sshkey file # check sshkey file
if [[ ! -e $sshkey_file ]]; then if [[ ! -e $sshkey_file ]]; then
expect -c " expect -c "
spawn ssh-keygen -t rsa spawn ssh-keygen -t rsa
@@ -1280,7 +1280,7 @@ function openim:util::setup_ssh_key_copy() {
# delete history # delete history
sed -i "/$target/d" ~/.ssh/known_hosts sed -i "/$target/d" ~/.ssh/known_hosts
# copy key # copy key
expect -c " expect -c "
set timeout 100 set timeout 100
spawn ssh-copy-id $username@$target spawn ssh-copy-id $username@$target
@@ -1571,7 +1571,7 @@ openim::util::check_ports() {
else else
start_time=$(ps -p $pid -o lstart=) start_time=$(ps -p $pid -o lstart=)
fi fi
started+=("Port $port - Command: $command, PID: $pid, FD: $fd, Started: $start_time") started+=("Port $port - Command: $command, PID: $pid, FD: $fd, Started: $start_time")
fi fi
done done
@@ -1639,7 +1639,7 @@ openim::util::check_process_names() {
for process_name in "$@"; do for process_name in "$@"; do
# Use `pgrep` to find process IDs related to the given process name # Use `pgrep` to find process IDs related to the given process name
local pids=($(pgrep -f $process_name)) local pids=($(pgrep -f $process_name))
# Check if any process IDs were found # Check if any process IDs were found
if [[ ${#pids[@]} -eq 0 ]]; then if [[ ${#pids[@]} -eq 0 ]]; then
not_started+=($process_name) not_started+=($process_name)
@@ -1713,7 +1713,7 @@ openim::util::stop_services_on_ports() {
# Extract the Process ID. # Extract the Process ID.
while read -r line; do while read -r line; do
local pid=$(echo $line | awk '{print $2}') local pid=$(echo $line | awk '{print $2}')
# Try to stop the service by killing its process. # Try to stop the service by killing its process.
if kill -TERM $pid; then if kill -TERM $pid; then
stopped+=($port) stopped+=($port)
@@ -1753,7 +1753,7 @@ openim::util::stop_services_on_ports() {
# nc -l -p 12345 # nc -l -p 12345
# nc -l -p 123456 # nc -l -p 123456
# ps -ef | grep "nc -l" # ps -ef | grep "nc -l"
# openim::util::stop_services_on_ports 1234 12345 # openim::util::stop_services_on_ports 1234 12345
# The `openim::util::stop_services_with_name` function stops services with specified names. # The `openim::util::stop_services_with_name` function stops services with specified names.
@@ -2320,7 +2320,7 @@ function openim::util::ensure-install-nginx {
exit 1 exit 1
fi fi
for port in "80" for port in 80
do do
if echo |telnet 127.0.0.1 $port 2>&1|grep refused &>/dev/null;then if echo |telnet 127.0.0.1 $port 2>&1|grep refused &>/dev/null;then
exit 1 exit 1
@@ -2467,7 +2467,7 @@ function openim::util::desc() {
} }
function openim::util:run::prompt() { function openim::util:run::prompt() {
echo -n "${yellow}\$ ${reset}" echo -n "$yellow\$ $reset"
} }
started="" started=""
@@ -2488,7 +2488,7 @@ function openim::util::run() {
if [ -n "$DEMO_RUN_FAST" ]; then if [ -n "$DEMO_RUN_FAST" ]; then
rate=1000 rate=1000
fi fi
echo "${green}$1${reset}" | pv -qL "$rate" echo "$green$1$reset" | pv -qL $rate
if [ -n "$DEMO_RUN_FAST" ]; then if [ -n "$DEMO_RUN_FAST" ]; then
sleep 0.5 sleep 0.5
fi fi
@@ -2516,7 +2516,7 @@ function openim::util::run::relative() {
# This function retrieves the IP address of the current server. # This function retrieves the IP address of the current server.
# It primarily uses the `curl` command to fetch the public IP address from ifconfig.me. # It primarily uses the `curl` command to fetch the public IP address from ifconfig.me.
# If curl or the service is not available, it falls back # If curl or the service is not available, it falls back
# to the internal IP address provided by the hostname command. # to the internal IP address provided by the hostname command.
# TODO: If a delay is found, the delay needs to be addressed # TODO: If a delay is found, the delay needs to be addressed
function openim::util::get_server_ip() { function openim::util::get_server_ip() {
@@ -2524,7 +2524,7 @@ function openim::util::get_server_ip() {
if command -v curl &> /dev/null; then if command -v curl &> /dev/null; then
# Try to retrieve the public IP address using curl and ifconfig.me # Try to retrieve the public IP address using curl and ifconfig.me
IP=$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | sed 's/"//g' | tr -d '\n') IP=$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | sed 's/"//g' | tr -d '\n')
# Check if IP retrieval was successful # Check if IP retrieval was successful
if [[ -z "$IP" ]]; then if [[ -z "$IP" ]]; then
# If not, get the internal IP address # If not, get the internal IP address
@@ -2534,7 +2534,7 @@ function openim::util::get_server_ip() {
# If curl is not available, get the internal IP address # If curl is not available, get the internal IP address
IP=$(ip addr show | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | cut -d'/' -f1 | head -n 1) IP=$(ip addr show | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | cut -d'/' -f1 | head -n 1)
fi fi
# Return the fetched IP address # Return the fetched IP address
echo "$IP" echo "$IP"
} }
@@ -2580,7 +2580,7 @@ function openim::util::set_max_fd() {
if [ "$desired_fd" = "maximum" ] || [ "$desired_fd" = "max" ]; then if [ "$desired_fd" = "maximum" ] || [ "$desired_fd" = "max" ]; then
desired_fd="$max_fd_limit" desired_fd="$max_fd_limit"
fi fi
# Check if desired_fd is less than or equal to max_fd_limit. # Check if desired_fd is less than or equal to max_fd_limit.
if [ "$desired_fd" -le "$max_fd_limit" ]; then if [ "$desired_fd" -le "$max_fd_limit" ]; then
ulimit -n "$desired_fd" ulimit -n "$desired_fd"
@@ -2696,7 +2696,7 @@ function openim::util::run::relative() {
# This function retrieves the IP address of the current server. # This function retrieves the IP address of the current server.
# It primarily uses the `curl` command to fetch the public IP address from ifconfig.me. # It primarily uses the `curl` command to fetch the public IP address from ifconfig.me.
# If curl or the service is not available, it falls back # If curl or the service is not available, it falls back
# to the internal IP address provided by the hostname command. # to the internal IP address provided by the hostname command.
# TODO: If a delay is found, the delay needs to be addressed # TODO: If a delay is found, the delay needs to be addressed
function openim::util::get_server_ip() { function openim::util::get_server_ip() {
@@ -2704,7 +2704,7 @@ function openim::util::get_server_ip() {
if command -v curl &> /dev/null; then if command -v curl &> /dev/null; then
# Try to retrieve the public IP address using curl and ifconfig.me # Try to retrieve the public IP address using curl and ifconfig.me
IP=$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | sed 's/"//g' | tr -d '\n') IP=$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | sed 's/"//g' | tr -d '\n')
# Check if IP retrieval was successful # Check if IP retrieval was successful
if [[ -z "$IP" ]]; then if [[ -z "$IP" ]]; then
# If not, get the internal IP address # If not, get the internal IP address
@@ -2714,7 +2714,7 @@ function openim::util::get_server_ip() {
# If curl is not available, get the internal IP address # If curl is not available, get the internal IP address
IP=$(ip addr show | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | cut -d'/' -f1 | head -n 1) IP=$(ip addr show | grep 'inet ' | grep -v 127.0.0.1 | awk '{print $2}' | cut -d'/' -f1 | head -n 1)
fi fi
# Return the fetched IP address # Return the fetched IP address
echo "$IP" echo "$IP"
} }
@@ -2760,7 +2760,7 @@ function openim::util::set_max_fd() {
if [ "$desired_fd" = "maximum" ] || [ "$desired_fd" = "max" ]; then if [ "$desired_fd" = "maximum" ] || [ "$desired_fd" = "max" ]; then
desired_fd="$max_fd_limit" desired_fd="$max_fd_limit"
fi fi
# Check if desired_fd is less than or equal to max_fd_limit. # Check if desired_fd is less than or equal to max_fd_limit.
if [ "$desired_fd" -le "$max_fd_limit" ]; then if [ "$desired_fd" -le "$max_fd_limit" ]; then
ulimit -n "$desired_fd" ulimit -n "$desired_fd"
+14 -14
View File
@@ -12,7 +12,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Version management helpers. These functions help to set, save and load the # Version management helpers. These functions help to set, save and load the
# following variables: # following variables:
@@ -35,7 +35,7 @@ openim::version::get_version_vars() {
openim::version::load_version_vars "${OPENIM_GIT_VERSION_FILE}" openim::version::load_version_vars "${OPENIM_GIT_VERSION_FILE}"
return return
fi fi
# If the iamrnetes source was exported through git archive, then # If the iamrnetes source was exported through git archive, then
# we likely don't have a git tree, but these magic values may be filled in. # we likely don't have a git tree, but these magic values may be filled in.
# shellcheck disable=SC2016,SC2050 # shellcheck disable=SC2016,SC2050
@@ -48,12 +48,12 @@ openim::version::get_version_vars() {
# something like 'HEAD -> release-1.8, tag: v1.8.3' where then 'tag: ' # something like 'HEAD -> release-1.8, tag: v1.8.3' where then 'tag: '
# can be extracted from it. # can be extracted from it.
if [[ '$Format:%D$' =~ tag:\ (v[^ ,]+) ]]; then if [[ '$Format:%D$' =~ tag:\ (v[^ ,]+) ]]; then
OPENIM_GIT_VERSION="${BASH_REMATCH[1]}" OPENIM_GIT_VERSION="${BASH_REMATCH[1]}"
fi fi
fi fi
local git=(git --work-tree "${OPENIM_ROOT}") local git=(git --work-tree "${OPENIM_ROOT}")
if [[ -n ${OPENIM_GIT_COMMIT-} ]] || OPENIM_GIT_COMMIT=$("${git[@]}" rev-parse "HEAD^{commit}" 2>/dev/null); then if [[ -n ${OPENIM_GIT_COMMIT-} ]] || OPENIM_GIT_COMMIT=$("${git[@]}" rev-parse "HEAD^{commit}" 2>/dev/null); then
if [[ -z ${OPENIM_GIT_TREE_STATE-} ]]; then if [[ -z ${OPENIM_GIT_TREE_STATE-} ]]; then
# Check if the tree is dirty. default to dirty # Check if the tree is dirty. default to dirty
@@ -63,7 +63,7 @@ openim::version::get_version_vars() {
OPENIM_GIT_TREE_STATE="dirty" OPENIM_GIT_TREE_STATE="dirty"
fi fi
fi fi
# Use git describe to find the version based on tags. # Use git describe to find the version based on tags.
if [[ -n ${OPENIM_GIT_VERSION-} ]] || OPENIM_GIT_VERSION=$("${git[@]}" describe --tags --always --match='v*' 2>/dev/null); then if [[ -n ${OPENIM_GIT_VERSION-} ]] || OPENIM_GIT_VERSION=$("${git[@]}" describe --tags --always --match='v*' 2>/dev/null); then
# This translates the "git describe" to an actual semver.org # This translates the "git describe" to an actual semver.org
@@ -81,7 +81,7 @@ openim::version::get_version_vars() {
# shellcheck disable=SC2001 # shellcheck disable=SC2001
# We have distance to subversion (v1.1.0-subversion-1-gCommitHash) # We have distance to subversion (v1.1.0-subversion-1-gCommitHash)
OPENIM_GIT_VERSION=$(echo "${OPENIM_GIT_VERSION}" | sed "s/-\([0-9]\{1,\}\)-g\([0-9a-f]\{14\}\)$/.\1\+\2/") OPENIM_GIT_VERSION=$(echo "${OPENIM_GIT_VERSION}" | sed "s/-\([0-9]\{1,\}\)-g\([0-9a-f]\{14\}\)$/.\1\+\2/")
elif [[ "${DASHES_IN_VERSION}" == "--" ]] ; then elif [[ "${DASHES_IN_VERSION}" == "--" ]] ; then
# shellcheck disable=SC2001 # shellcheck disable=SC2001
# We have distance to base tag (v1.1.0-1-gCommitHash) # We have distance to base tag (v1.1.0-1-gCommitHash)
OPENIM_GIT_VERSION=$(echo "${OPENIM_GIT_VERSION}" | sed "s/-g\([0-9a-f]\{14\}\)$/+\1/") OPENIM_GIT_VERSION=$(echo "${OPENIM_GIT_VERSION}" | sed "s/-g\([0-9a-f]\{14\}\)$/+\1/")
@@ -94,7 +94,7 @@ openim::version::get_version_vars() {
#OPENIM_GIT_VERSION+="-dirty" #OPENIM_GIT_VERSION+="-dirty"
: :
fi fi
# Try to match the "git describe" output to a regex to try to extract # Try to match the "git describe" output to a regex to try to extract
# the "major" and "minor" versions and whether this is the exact tagged # the "major" and "minor" versions and whether this is the exact tagged
# version or whether the tree is between two tagged versions. # version or whether the tree is between two tagged versions.
@@ -105,12 +105,12 @@ openim::version::get_version_vars() {
OPENIM_GIT_MINOR+="+" OPENIM_GIT_MINOR+="+"
fi fi
fi fi
# If OPENIM_GIT_VERSION is not a valid Semantic Version, then refuse to build. # If OPENIM_GIT_VERSION is not a valid Semantic Version, then refuse to build.
if ! [[ "${OPENIM_GIT_VERSION}" =~ ^v([0-9]+)\.([0-9]+)(\.[0-9]+)?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then if ! [[ "${OPENIM_GIT_VERSION}" =~ ^v([0-9]+)\.([0-9]+)(\.[0-9]+)?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then
echo "OPENIM_GIT_VERSION should be a valid Semantic Version. Current value: ${OPENIM_GIT_VERSION}" echo "OPENIM_GIT_VERSION should be a valid Semantic Version. Current value: ${OPENIM_GIT_VERSION}"
echo "Please see more details here: https://semver.org" echo "Please see more details here: https://semver.org"
exit 1 exit 1
fi fi
fi fi
fi fi
@@ -123,7 +123,7 @@ openim::version::save_version_vars() {
echo "!!! Internal error. No file specified in openim::version::save_version_vars" echo "!!! Internal error. No file specified in openim::version::save_version_vars"
return 1 return 1
} }
cat <<EOF >"${version_file}" cat <<EOF >"${version_file}"
OPENIM_GIT_COMMIT='${OPENIM_GIT_COMMIT-}' OPENIM_GIT_COMMIT='${OPENIM_GIT_COMMIT-}'
OPENIM_GIT_TREE_STATE='${OPENIM_GIT_TREE_STATE-}' OPENIM_GIT_TREE_STATE='${OPENIM_GIT_TREE_STATE-}'
@@ -140,6 +140,6 @@ openim::version::load_version_vars() {
echo "!!! Internal error. No file specified in openim::version::load_version_vars" echo "!!! Internal error. No file specified in openim::version::load_version_vars"
return 1 return 1
} }
source "${version_file}" source "${version_file}"
} }
+1 -1
View File
@@ -126,7 +126,7 @@ APIROOT=$(ROOT_DIR)/pkg/proto
# Linux command settings # Linux command settings
# TODO: Whether you need to join utils? # TODO: Whether you need to join utils?
FIND := find . ! -path './utils/*' ! -path './vendor/*' ! -path './third_party/*' ! -path './components/*' ! -path './logs/*' FIND := find . ! -path './utils/*' ! -path './vendor/*' ! -path './third_party/*'
XARGS := xargs -r --no-run-if-empty XARGS := xargs -r --no-run-if-empty
# Linux command settings-CODE DIRS Copyright # Linux command settings-CODE DIRS Copyright
+1 -1
View File
@@ -244,7 +244,7 @@ go.imports: tools.verify.goimports
## go.verify: execute all verity scripts. ## go.verify: execute all verity scripts.
.PHONY: go.verify .PHONY: go.verify
go.verify: tools.verify.misspell go.verify:
@echo "Starting verification..." @echo "Starting verification..."
@scripts_list=$$(find $(ROOT_DIR)/scripts -type f -name 'verify-*' | sort); \ @scripts_list=$$(find $(ROOT_DIR)/scripts -type f -name 'verify-*' | sort); \
for script in $$scripts_list; do \ for script in $$scripts_list; do \
+1 -2
View File
@@ -45,8 +45,7 @@ endif
IMAGES_DIR ?= $(wildcard ${ROOT_DIR}/build/images/*) IMAGES_DIR ?= $(wildcard ${ROOT_DIR}/build/images/*)
# Determine images names by stripping out the dir names, and filter out the undesired directories # Determine images names by stripping out the dir names, and filter out the undesired directories
# IMAGES ?= $(filter-out Dockerfile,$(foreach image,${IMAGES_DIR},$(notdir ${image}))) # IMAGES ?= $(filter-out Dockerfile,$(foreach image,${IMAGES_DIR},$(notdir ${image})))
IMAGES ?= $(filter-out Dockerfile openim-tools openim-rpc-extend-msg openim-rpc-encryption openim-cmdutils,$(foreach image,${IMAGES_DIR},$(notdir ${image}))) IMAGES ?= $(filter-out Dockerfile openim-tools openim-cmdutils,$(foreach image,${IMAGES_DIR},$(notdir ${image})))
# IMAGES ?= $(filter-out Dockerfile openim-tools openim-cmdutils,$(foreach image,${IMAGES_DIR},$(notdir ${image}))) # !pro
ifeq (${IMAGES},) ifeq (${IMAGES},)
$(error Could not determine IMAGES, set ROOT_DIR or run in source dir) $(error Could not determine IMAGES, set ROOT_DIR or run in source dir)
-5
View File
@@ -217,11 +217,6 @@ install.depth:
install.go-callvis: install.go-callvis:
@$(GO) install github.com/ofabry/go-callvis@latest @$(GO) install github.com/ofabry/go-callvis@latest
## install.misspell
.PHONY: install.misspell
install.misspell:
@$(GO) install github.com/client9/misspell/cmd/misspell@latest
## install.gothanks: Install gothanks, used to thank go dependencies ## install.gothanks: Install gothanks, used to thank go dependencies
.PHONY: install.gothanks .PHONY: install.gothanks
install.gothanks: install.gothanks:
+58 -58
View File
@@ -14,9 +14,9 @@
# limitations under the License. # limitations under the License.
# Description: # Description:
# This script automates the process of building and releasing OpenIM, # This script automates the process of building and releasing OpenIM,
# including tasks like setting up the environment, verifying prerequisites, # including tasks like setting up the environment, verifying prerequisites,
# building commands, packaging tarballs, uploading tarballs, creating GitHub # building commands, packaging tarballs, uploading tarballs, creating GitHub
# releases, and generating changelogs. # releases, and generating changelogs.
# #
# Usage: # Usage:
@@ -35,12 +35,12 @@
# This script can also be executed via the 'make release' command as an alternative. # This script can also be executed via the 'make release' command as an alternative.
# #
# Dependencies: # Dependencies:
# This script depends on external scripts found in the 'scripts' directory and # This script depends on external scripts found in the 'scripts' directory and
# assumes the presence of necessary tools and permissions for building and # assumes the presence of necessary tools and permissions for building and
# releasing software. # releasing software.
# #
# Note: # Note:
# The script uses standard bash script practices with error handling, # The script uses standard bash script practices with error handling,
# and it defaults to executing all steps if no specific option is provided. # and it defaults to executing all steps if no specific option is provided.
# #
# Build a OpenIM release. This will build the binaries, create the Docker # Build a OpenIM release. This will build the binaries, create the Docker
@@ -58,17 +58,17 @@ OPENIM_RELEASE_RUN_TESTS=${OPENIM_RELEASE_RUN_TESTS-y}
# Function to show help message # Function to show help message
show_help() { show_help() {
echo "Usage: $(basename $0) [options]" echo "Usage: $(basename $0) [options]"
echo "Options:" echo "Options:"
echo " -h, --help Show this help message" echo " -h, --help Show this help message"
echo " -se, --setup-env Execute setup environment" echo " -se, --setup-env Execute setup environment"
echo " -vp, --verify-prereqs Execute prerequisites verification" echo " -vp, --verify-prereqs Execute prerequisites verification"
echo " -bc, --build-command Execute build command" echo " -bc, --build-command Execute build command"
echo " -bi, --build-image Execute build image (default: not executed)" echo " -bi, --build-image Execute build image (default: not executed)"
echo " -pt, --package-tarballs Execute package tarballs" echo " -pt, --package-tarballs Execute package tarballs"
echo " -ut, --upload-tarballs Execute upload tarballs" echo " -ut, --upload-tarballs Execute upload tarballs"
echo " -gr, --github-release Execute GitHub release" echo " -gr, --github-release Execute GitHub release"
echo " -gc, --generate-changelog Execute generate changelog" echo " -gc, --generate-changelog Execute generate changelog"
} }
# Initialize all actions to false # Initialize all actions to false
@@ -83,57 +83,57 @@ perform_generate_changelog=false
# Process command-line arguments # Process command-line arguments
while getopts "hsevpbciptutgrgc-" opt; do while getopts "hsevpbciptutgrgc-" opt; do
case "${opt}" in case "${opt}" in
h) show_help; exit 0 ;; h) show_help; exit 0 ;;
se) perform_setup_env=true ;; se) perform_setup_env=true ;;
vp) perform_verify_prereqs=true ;; vp) perform_verify_prereqs=true ;;
bc) perform_build_command=true ;; bc) perform_build_command=true ;;
bi) perform_build_image=true ;; # Handling new option bi) perform_build_image=true ;; # Handling new option
pt) perform_package_tarballs=true ;; pt) perform_package_tarballs=true ;;
ut) perform_upload_tarballs=true ;; ut) perform_upload_tarballs=true ;;
gr) perform_github_release=true ;; gr) perform_github_release=true ;;
gc) perform_generate_changelog=true ;; gc) perform_generate_changelog=true ;;
--) case "${OPTARG}" in --) case "${OPTARG}" in
help) show_help; exit 0 ;; help) show_help; exit 0 ;;
setup-env) perform_setup_env=true ;; setup-env) perform_setup_env=true ;;
verify-prereqs) perform_verify_prereqs=true ;; verify-prereqs) perform_verify_prereqs=true ;;
build-command) perform_build_command=true ;; build-command) perform_build_command=true ;;
build-image) perform_build_image=true ;; # Handling new long option build-image) perform_build_image=true ;; # Handling new long option
package-tarballs) perform_package_tarballs=true ;; package-tarballs) perform_package_tarballs=true ;;
upload-tarballs) perform_upload_tarballs=true ;; upload-tarballs) perform_upload_tarballs=true ;;
github-release) perform_github_release=true ;; github-release) perform_github_release=true ;;
generate-changelog) perform_generate_changelog=true ;; generate-changelog) perform_generate_changelog=true ;;
*) echo "Invalid option: --${OPTARG}"; show_help; exit 1 ;; *) echo "Invalid option: --${OPTARG}"; show_help; exit 1 ;;
esac ;; esac ;;
*) show_help; exit 1 ;; *) show_help; exit 1 ;;
esac esac
done done
# Enable all actions by default if no options are provided # Enable all actions by default if no options are provided
if [ "$#" -eq 0 ]; then if [ "$#" -eq 0 ]; then
perform_setup_env=true perform_setup_env=true
perform_verify_prereqs=true perform_verify_prereqs=true
perform_build_command=true perform_build_command=true
perform_package_tarballs=true perform_package_tarballs=true
perform_upload_tarballs=true perform_upload_tarballs=true
perform_github_release=true perform_github_release=true
perform_generate_changelog=true perform_generate_changelog=true
# TODO: Not enabling build_image by default # TODO: Not enabling build_image by default
# perform_build_image=true # perform_build_image=true
fi fi
# Function to perform actions # Function to perform actions
perform_action() { perform_action() {
local flag=$1 local flag=$1
local message=$2 local message=$2
local command=$3 local command=$3
if [ "$flag" == true ]; then if [ "$flag" == true ]; then
openim::log::info "## $message..." openim::log::info "## $message..."
if ! eval "$command"; then if ! $command; then
openim::log::errexit "Error in $message" openim::log::errexit "Error in $message"
fi
fi fi
fi
} }
echo "Starting script execution..." echo "Starting script execution..."
+28 -28
View File
@@ -39,34 +39,34 @@ openim::log::install_errexit
# Function to execute the scripts. # Function to execute the scripts.
function execute_scripts() { function execute_scripts() {
for script_path in "${OPENIM_SERVER_SCRIPT_START_LIST[@]}"; do for script_path in "${OPENIM_SERVER_SCRIPT_START_LIST[@]}"; do
# Extract the script name without extension for argument generation. # Extract the script name without extension for argument generation.
script_name_with_prefix=$(basename "$script_path" .sh) script_name_with_prefix=$(basename "$script_path" .sh)
# Remove the "openim-" prefix. # Remove the "openim-" prefix.
script_name=${script_name_with_prefix#openim-} script_name=${script_name_with_prefix#openim-}
# Construct the argument based on the script name. # Construct the argument based on the script name.
arg="openim::${script_name}::start" arg="openim::${script_name}::start"
# Check if the script file exists and is executable. # Check if the script file exists and is executable.
if [[ -x "$script_path" ]]; then if [[ -x "$script_path" ]]; then
openim::log::status "Starting script: ${script_path##*/}" # Log the script name. openim::log::status "Starting script: ${script_path##*/}" # Log the script name.
# Execute the script with the constructed argument. # Execute the script with the constructed argument.
"$script_path" "$arg" "$script_path" "$arg"
# Check if the script executed successfully. # Check if the script executed successfully.
if [[ $? -eq 0 ]]; then if [[ $? -eq 0 ]]; then
openim::log::info "${script_path##*/} executed successfully." openim::log::info "${script_path##*/} executed successfully."
else else
openim::log::errexit "Error executing ${script_path##*/}." openim::log::errexit "Error executing ${script_path##*/}."
fi fi
else else
openim::log::errexit "Script ${script_path##*/} is missing or not executable." openim::log::errexit "Script ${script_path##*/} is missing or not executable."
fi fi
done done
sleep 0.5 sleep 0.5
} }
+3 -3
View File
@@ -14,7 +14,7 @@
# limitations under the License. # limitations under the License.
# This script is stop all openim service # This script is stop all openim service
# #
# Usage: `scripts/stop.sh`. # Usage: `scripts/stop.sh`.
# Encapsulated as: `make stop`. # Encapsulated as: `make stop`.
@@ -38,8 +38,8 @@ openim::util::stop_services_with_name "${OPENIM_OUTPUT_HOSTBIN}"
echo -n "Stopping services 15 seconds." echo -n "Stopping services 15 seconds."
for i in {1..15}; do for i in {1..15}; do
echo -n "." echo -n "."
sleep 1 sleep 1
done done
echo -e "\nServices stopped." echo -e "\nServices stopped."

Some files were not shown because too many files have changed in this diff Show More