-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.py
More file actions
207 lines (154 loc) · 5.6 KB
/
Copy pathdb.py
File metadata and controls
207 lines (154 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import enum
import datetime
import config_parsing
from utils import mac_regex, ensure_ztp_mac
from config import db_url, ztp_network, ztp_interface_ip
from sqlalchemy import (
create_engine,
Column,
Integer,
String,
Enum,
ForeignKey,
DateTime,
)
from sqlalchemy.orm import declarative_base, sessionmaker, scoped_session, relationship
Base = declarative_base()
_engine = create_engine(db_url)
def create_scoped_session():
engine = create_engine(db_url)
session_factory = sessionmaker(bind=engine)
return scoped_session(session_factory)
Session = create_scoped_session()
class SwitchStatus(enum.Enum):
CREATED = 0
NAMED = 1
DHCP_SUCCESS = 2
REBOOTING = 3
FINISHED = 4
ERROR = 100
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
return NotImplemented
def __gt__(self, other):
if self.__class__ is other.__class__:
return self.value > other.value
return NotImplemented
class Switch(Base):
__tablename__ = "switches"
id = Column(Integer, primary_key=True)
mac = Column(String, nullable=False)
name = Column(String)
status = Column(Enum(SwitchStatus), default=SwitchStatus.CREATED)
ztp_ip = Column(String)
final_ip = Column(
String
) # The IP of service port 1 which is assigned by the config file
finished_date = Column(DateTime)
def __repr__(self):
return (
f'<MAC="{self.mac}", NAME="{self.name}", STATUS="{self.status.name}", '
+ f'ZTP_IP="{self.ztp_ip}", FINAL_IP="{self.final_ip}">'
)
class SyslogEntry(Base):
__tablename__ = "syslog"
id = Column(Integer, primary_key=True)
msg = Column(String)
switch_id = Column(Integer, ForeignKey("switches.id"))
switch = relationship("Switch", back_populates="syslog_entries")
Switch.syslog_entries = relationship(
"SyslogEntry", order_by=SyslogEntry.id, back_populates="switch"
)
def init_db():
Base.metadata.create_all(_engine)
def get_next_ip():
with Session() as session:
used_ips = [sw.ztp_ip for sw in session.query(Switch.ztp_ip).all()]
used_ips.append(ztp_interface_ip)
for ip in ztp_network.hosts():
if not ip.exploded in used_ips:
return ip.exploded
def add_switch(mac):
mac = ensure_ztp_mac(mac)
switch = Switch(mac=mac, ztp_ip=str(get_next_ip()))
with Session() as session:
session.add(switch)
session.commit()
def query_mac(mac):
mac = ensure_ztp_mac(mac)
with Session() as session:
return session.query(Switch).filter(Switch.mac == mac).scalar()
def query_name(name):
with Session() as session:
return session.query(Switch).filter(Switch.name == name).first()
def get_macs_names():
with Session() as session:
switches = session.query(Switch.mac, Switch.name).all()
macs = [sw[0] for sw in switches]
names = [sw[1] for sw in switches if sw[1] is not None]
return macs, names
def _fill_final_ip(switch):
ip, _ = config_parsing.get_ip_and_network_port_1(switch.name)
if ip is None:
print(
"Warning: Switch has no IP assigned on port 1.\n"
+ "It will not be possible to check when ZTP is finished.\n"
+ "Please observe this switch manually."
)
return
switch.final_ip = ip.exploded
def name_switch(mac, name):
mac = ensure_ztp_mac(mac)
with Session() as session:
existing = session.query(Switch).filter(Switch.name == name).all()
if len(existing) > 0:
raise ValueError(f"Name {name} already used by switch {existing[0].mac}")
sw = session.query(Switch).filter(Switch.mac == mac).one()
if sw.name is not None:
print(f"Error: Switch {mac} already named {sw.name}")
return
sw.name = name
sw.status = SwitchStatus.NAMED
_fill_final_ip(sw)
session.commit()
def name_last_added_switch(name):
with Session() as session:
sw = session.query(Switch).order_by(Switch.id.desc()).first()
name_switch(sw.mac, name)
def query_all_unfinished_switches():
with Session() as session:
return (
session.query(Switch)
.filter(Switch.status != SwitchStatus.FINISHED)
.filter(Switch.name is not None)
.all()
)
def get_syslog_entries(mac_or_name):
with Session() as session:
if mac_regex.match(mac_or_name):
mac = ensure_ztp_mac(mac_or_name)
switch = session.query(Switch).filter(Switch.mac == mac).one()
else:
switch = session.query(Switch).filter(Switch.name == mac_or_name).one()
return [le.msg for le in switch.syslog_entries]
def remove_switch(mac_or_name):
with Session() as session:
if mac_regex.match(mac_or_name):
mac = ensure_ztp_mac(mac_or_name)
switch = session.query(Switch).filter(Switch.mac == mac).one()
else:
switch = session.query(Switch).filter(Switch.name == mac_or_name).one()
session.delete(switch)
session.commit()
def set_status(mac_or_name, status: str):
with Session() as session:
if mac_regex.match(mac_or_name):
mac = ensure_ztp_mac(mac_or_name)
switch = session.query(Switch).filter(Switch.mac == mac).one()
else:
switch = session.query(Switch).filter(Switch.name == mac_or_name).one()
switch.status = SwitchStatus[status.upper()]
if switch.status == SwitchStatus.FINISHED:
switch.finished_date = datetime.now()
session.commit()