-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcluster_setup_basic.py
More file actions
295 lines (254 loc) · 10.1 KB
/
cluster_setup_basic.py
File metadata and controls
295 lines (254 loc) · 10.1 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env python3
# © 2026 NetApp, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# See the NOTICE file in the repo root for trademark and attribution details.
"""Create a storage cluster from two pre-cluster nodes.
Steps:
1. discover_nodes — GET /api/cluster/nodes (membership=available, retry 3x/30s)
2. discover_local — isolate the local node (has management_interfaces != null)
3. discover_partner — isolate the partner node (exclude local node UUID)
4. create_cluster — POST /api/cluster
5. track_job — poll job until state != running
Usage::
# env vars directly
export ONTAP_HOST=10.x.x.x # pre-cluster node IP
export ONTAP_USER=admin # usually admin, empty pass on pre-cluster nodes
export ONTAP_PASS=
export CLUSTER_NAME=mycluster
export CLUSTER_PASS=<your-password>
export CLUSTER_MGMT_IP=10.x.x.x
export CLUSTER_NETMASK=255.255.192.0
export CLUSTER_GATEWAY=10.x.x.1
export PARTNER_MGMT_IP=10.x.x.y
python cluster_setup_basic.py
"""
from __future__ import annotations
import argparse
import logging
import os
import sys
import time
from pathlib import Path
from ontap_client import OntapClient
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# USER INPUTS — fill in your values here before running
# ---------------------------------------------------------------------------
INPUTS = {
"ONTAP_HOST": "", # Node 1 management IP — set via ONTAP_HOST env var
"ONTAP_USER": "admin",
"ONTAP_PASS": "", # leave empty for pre-cluster nodes
"CLUSTER_NAME": "", # set via CLUSTER_NAME env var
"CLUSTER_PASS": "", # set via CLUSTER_PASS env var — choose your cluster admin password
"CLUSTER_MGMT_IP": "", # cluster management IP — set via CLUSTER_MGMT_IP env var
"CLUSTER_NETMASK": "", # set via CLUSTER_NETMASK env var
"CLUSTER_GATEWAY": "", # default gateway — set via CLUSTER_GATEWAY env var
"PARTNER_MGMT_IP": "", # Node 2 management IP — set via PARTNER_MGMT_IP env var
}
# ---------------------------------------------------------------------------
_NODE_FIELDS_SETS = [
# newest (9.19+)
(
"name,model,state,ha,version,serial_number,membership,"
"cluster_interfaces,management_interfaces,metrocluster,disaggregated,san_optimized"
),
# 9.18 without disaggregated
(
"name,model,state,ha,version,serial_number,membership,"
"cluster_interfaces,management_interfaces,metrocluster,san_optimized"
),
# 9.14 and older — minimal safe set
(
"name,model,state,ha,version,serial_number,membership,"
"cluster_interfaces,management_interfaces,metrocluster"
),
]
def _env(key: str, required: bool = True) -> str:
val = INPUTS.get(key) or os.environ.get(key, "")
if required and not val:
logger.error(
"Input '%s' is required — set it in the INPUTS block at the top of this file",
key,
)
sys.exit(1)
return val
# ---------------------------------------------------------------------------
# Steps
# ---------------------------------------------------------------------------
def _get_nodes(client: OntapClient, **kwargs) -> dict:
"""GET /cluster/nodes, trying progressively reduced field sets for older ONTAP versions."""
last_exc: Exception | None = None
for fields in _NODE_FIELDS_SETS:
try:
return client.get("/cluster/nodes", fields=fields, **kwargs)
except Exception as exc:
if "262197" in str(exc):
logger.warning(
"discover: field unsupported on this version, retrying with reduced fields"
)
last_exc = exc
continue
raise
raise last_exc # type: ignore[misc]
def discover_nodes(client: OntapClient, attempts: int = 3, delay: int = 30) -> dict:
"""Step 1 — discover available nodes, retry up to 3 times."""
for attempt in range(1, attempts + 1):
try:
result = _get_nodes(client, membership="available")
logger.info("discover_nodes — %d node(s) found", result.get("num_records", 0))
return result
except Exception as exc:
if attempt < attempts:
logger.warning(
"discover_nodes failed (attempt %d/%d), retrying in %ds — %s",
attempt,
attempts,
delay,
exc,
)
time.sleep(delay)
else:
raise RuntimeError(f"discover_nodes failed after {attempts} attempts") from exc
def discover_local(client: OntapClient) -> dict:
"""Step 2 — isolate the local node (management_interfaces != null)."""
result = _get_nodes(
client,
membership="available",
**{"management_interfaces": "!null"},
)
records = result.get("records", [])
if not records:
raise RuntimeError("discover_local: no local node returned")
logger.info("discover_local — %s", records[0]["name"])
return result
def discover_partner(client: OntapClient, local_uuid: str) -> dict:
"""Step 3 — isolate the partner node (exclude local UUID)."""
result = _get_nodes(
client,
membership="available",
**{"uuid": f"!{local_uuid}"},
)
records = result.get("records", [])
if not records:
raise RuntimeError("discover_partner: no partner node returned")
logger.info("discover_partner — %s", records[0]["name"])
return result
def create_cluster(client: OntapClient, local: dict, partner: dict) -> dict:
"""Step 4 — POST /api/cluster to create the cluster."""
cluster_name = _env("CLUSTER_NAME")
cluster_pass = _env("CLUSTER_PASS")
cluster_mgmt_ip = _env("CLUSTER_MGMT_IP")
cluster_netmask = _env("CLUSTER_NETMASK")
cluster_gateway = _env("CLUSTER_GATEWAY")
ontap_host = _env("ONTAP_HOST")
partner_mgmt_ip = _env("PARTNER_MGMT_IP")
local_node = local["records"][0]
partner_node = partner["records"][0]
body = {
"name": cluster_name,
"password": cluster_pass,
"management_interface": {
"ip": {
"address": cluster_mgmt_ip,
"netmask": cluster_netmask,
"gateway": cluster_gateway,
}
},
"nodes": [
{
"name": f"{cluster_name}-01",
"management_interface": {"ip": {"address": ontap_host}},
"cluster_interface": {
"ip": {"address": local_node["cluster_interfaces"][0]["ip"]["address"]}
},
},
{
"name": f"{cluster_name}-02",
"management_interface": {"ip": {"address": partner_mgmt_ip}},
"cluster_interface": {
"ip": {"address": partner_node["cluster_interfaces"][0]["ip"]["address"]}
},
},
],
"name_servers": {},
"ntp_servers": {},
"dns_domains": {},
"configuration_backup": {},
}
result = client.post("/cluster?keep_precluster_config=true", body)
job_uuid = result.get("job", {}).get("uuid")
logger.info("create_cluster — job %s", job_uuid)
return result
def track_job(client: OntapClient, job_uuid: str) -> dict:
"""Step 5 — poll job until state != running (switch to cluster password first)."""
# After cluster creation the node switches to cluster mode — use CLUSTER_PASS
client._session.auth = (_env("ONTAP_USER"), _env("CLUSTER_PASS"))
while True:
result = client.get(
f"/cluster/jobs/{job_uuid}",
fields=("code,description,end_time,error,message,start_time,state,uuid"),
)
state = result.get("state", "unknown")
logger.info("track_job — state=%s", state)
if state != "running":
if state != "success":
raise RuntimeError(
f"Cluster job ended with state='{state}': {result.get('error')}"
)
return result
time.sleep(10)
def main() -> None:
host = _env("ONTAP_HOST")
user = _env("ONTAP_USER")
passwd = os.environ.get("ONTAP_PASS", "") # empty on pre-cluster nodes
logger.info("Cluster setup starting — connecting to %s", host)
with OntapClient(host, user, passwd, verify_ssl=False, timeout=150) as client:
discover_nodes(client)
local = discover_local(client)
partner = discover_partner(client, local["records"][0]["uuid"])
job = create_cluster(client, local, partner)
track_job(client, job["job"]["uuid"])
cluster_name = _env("CLUSTER_NAME")
cluster_mgmt_ip = _env("CLUSTER_MGMT_IP")
logger.info(
"Cluster '%s' created — UI: https://%s login: %s / %s",
cluster_name,
cluster_mgmt_ip,
_env("ONTAP_USER"),
_env("CLUSTER_PASS"),
)
def _load_env_file(path: str) -> None:
"""Load KEY=VALUE pairs from a .env file into the INPUTS dict."""
for line in Path(path).read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
INPUTS[key.strip()] = value.strip().strip('"').strip("'")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Create an ONTAP cluster from two pre-cluster nodes."
)
parser.add_argument(
"--env-file",
metavar="FILE",
help="Path to a .env file with KEY=VALUE pairs (one per build, like -ir in ha_create.exp).",
)
args = parser.parse_args()
if args.env_file:
_load_env_file(args.env_file)
for key in list(INPUTS):
val = os.environ.get(key)
if val:
INPUTS[key] = val
try:
main()
except KeyboardInterrupt:
sys.exit(130)
except Exception:
logger.exception("cluster_setup_basic failed")
sys.exit(1)