__init__.py 4.07 KB
Newer Older
1
2
3
import redis
import toml
import os
BO ZHANG's avatar
BO ZHANG committed
4
from astropy.table import Table
BO ZHANG's avatar
BO ZHANG committed
5
import socket
6

BO ZHANG's avatar
BO ZHANG committed
7
CONFIG = toml.load(os.path.join(os.path.dirname(__file__), "config.toml"))
8
9


BO ZHANG's avatar
BO ZHANG committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def check_port(ip, port, timeout=3):
    """
    # # 示例:检查 192.168.1.1 的 80 端口是否开放
    # print(check_port("192.168.1.1", 80))  # True/False
    """
    try:
        # 创建 Socket 连接(TCP)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)  # 设置超时时间(秒)
        # 尝试连接
        result = sock.connect_ex((ip, port))
        # 返回状态
        if result == 0:  # 0 表示成功
            return True
        else:
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False
    finally:
        sock.close()  # 确保关闭连接


33
class DFS:
BO ZHANG's avatar
BO ZHANG committed
34
35
    def __init__(self, location=None):
        # try each location
BO ZHANG's avatar
BO ZHANG committed
36
        print("Test all locations...", end="")
BO ZHANG's avatar
BO ZHANG committed
37
38
        status_list = []
        for loc in CONFIG.keys():
BO ZHANG's avatar
BO ZHANG committed
39
40
            dfs_ip = CONFIG[loc]["CSST_DFS_GATEWAY"].split(":")[0]
            dfs_port = int(CONFIG[loc]["CSST_DFS_GATEWAY"].split(":")[1])
BO ZHANG's avatar
BO ZHANG committed
41
42
            # redis_ip = CONFIG[loc]["redis"]["host"]
            # redis_port = CONFIG[loc]["redis"]["port"]
BO ZHANG's avatar
BO ZHANG committed
43
            this_dfs_status = check_port(dfs_ip, dfs_port, timeout=1)
BO ZHANG's avatar
BO ZHANG committed
44
            # this_redis_status = check_port(redis_ip, redis_port, timeout=1)
BO ZHANG's avatar
BO ZHANG committed
45
46
            this_status = dict(
                location=loc,
BO ZHANG's avatar
BO ZHANG committed
47
                status=this_dfs_status,  # and this_redis_status,
BO ZHANG's avatar
BO ZHANG committed
48
                dfs=this_dfs_status,
BO ZHANG's avatar
BO ZHANG committed
49
                # redis=this_redis_status,
BO ZHANG's avatar
BO ZHANG committed
50
51
            )
            status_list.append(this_status)
BO ZHANG's avatar
BO ZHANG committed
52
53
            # print(this_status)
        print("Done!\n")
BO ZHANG's avatar
BO ZHANG committed
54
55
        status_table = Table(status_list)
        print(status_table)
BO ZHANG's avatar
BO ZHANG committed
56
        print("\n")
BO ZHANG's avatar
BO ZHANG committed
57
        if status_table["status"].sum() == 0:
BO ZHANG's avatar
BO ZHANG committed
58
            print("No DFS location is available")
BO ZHANG's avatar
BO ZHANG committed
59
60
        elif status_table["status"].sum() > 1:
            print("Multiple DFS locations are available, please specify one")
BO ZHANG's avatar
BO ZHANG committed
61
62
63
64
        elif location is None:
            # set DFS automatically
            if status_table["status"].sum() == 1:
                print("One DFS locations are available, good")
BO ZHANG's avatar
BO ZHANG committed
65
                location = status_table["location"][status_table["status"]][0]
BO ZHANG's avatar
BO ZHANG committed
66
67
68
69
70
71
            elif status_table["status"].sum() == 0:
                print("No DFS location is available, using csu")
                location = "csu"
            else:
                raise ValueError("Multiple DFS locations are available")

BO ZHANG's avatar
BO ZHANG committed
72
            self.location = location
BO ZHANG's avatar
BO ZHANG committed
73
            self.config = CONFIG[self.location]
BO ZHANG's avatar
BO ZHANG committed
74

BO ZHANG's avatar
BO ZHANG committed
75
            for k, v in CONFIG[self.location].items():
BO ZHANG's avatar
BO ZHANG committed
76
77
                os.environ.setdefault(k, str(v))
            # print("Setting redis config:")
BO ZHANG's avatar
BO ZHANG committed
78
            # self.redis = Redis(location=self.location)
79
80
81


class Redis(redis.Redis):
BO ZHANG's avatar
BO ZHANG committed
82
    def __init__(self, location="naoc", **kwargs):
83
84
85
86
87
88
89
90
        if location not in CONFIG.keys():
            print("Available redis locations: ", list(CONFIG.keys()))
            raise ValueError(f"Unknown redis location: {location}")
        super().__init__(
            host=CONFIG[location]["redis"]["host"],
            port=CONFIG[location]["redis"]["port"],
            db=CONFIG[location]["redis"]["db"],
            password=CONFIG[location]["redis"]["password"],
BO ZHANG's avatar
BO ZHANG committed
91
            **kwargs,
92
93
94
        )
        self.qname = password = CONFIG[location]["redis"]["qname"]
        self.config = CONFIG[location]["redis"]
BO ZHANG's avatar
BO ZHANG committed
95
96
97
        # print("Setting redis config:")
        # for k, v in self.config.items():
        #     print(f" - {k}: {v}")
98
99
100
101
102
103
104
105
106
107
108

    def push(self, msg):
        self.lpush(self.qname, msg)

    def pop(self):
        return self.rpop(self.qname)

    def get_all(self):
        return self.lrange(self.qname, 0, -1)


BO ZHANG's avatar
BO ZHANG committed
109
110
dfs = DFS(location=None)

111
112
113
# msgs = r.lrange(name, 0, -1)
# for chipid in range(6, 26):
#     this_msg = gen_msg(
BO ZHANG's avatar
BO ZHANG committed
114
#         dag="csst-msc-l1-mbi", obsid="11009101682009", chipid=f"{chipid:02d}"
115
116
117
118
119
120
121
122
123
#     )
#     print(this_msg)
#     r.lpush(name, this_msg)
#
# msgs = r.lrange(name, 0, -1)
# print(msgs)
#
# msgs_later = r.lrange(name, 0, -1)
# print(msgs_later)