0
# Fabric Support
1
2
Integration with MySQL Fabric for high availability and scaling, supporting automatic failover, load balancing, and sharding configurations.
3
4
## Capabilities
5
6
### Fabric Connection
7
8
Create and manage MySQL Fabric connections for high availability and scalability.
9
10
```python { .api }
11
def connect(**config):
12
"""
13
Create MySQL Fabric connection with high availability support.
14
15
Parameters:
16
- fabric (dict): Fabric configuration with host, port, user, password
17
- group (str): Server group name for connection routing
18
- key (str): Sharding key for database sharding
19
- tables (list): Tables to include in sharding scope
20
- mode (int): Connection mode (MODE_READONLY or MODE_READWRITE)
21
- attempts (int): Number of connection attempts (default: 3)
22
- attempt_delay (int): Delay between attempts in seconds (default: 1)
23
- **config: Additional MySQL connection parameters
24
25
Returns:
26
MySQLFabricConnection: Fabric-aware connection object
27
28
Raises:
29
InterfaceError: Fabric connection failed
30
"""
31
32
MODE_READONLY = 1
33
MODE_READWRITE = 2
34
35
class MySQLFabricConnection:
36
"""
37
MySQL Fabric connection wrapper providing high availability features.
38
39
Manages connections to MySQL Fabric infrastructure for automatic
40
failover, load balancing, and database sharding across multiple
41
MySQL server instances.
42
"""
43
44
def __init__(self, **config):
45
"""
46
Initialize Fabric connection.
47
48
Parameters:
49
- **config: Fabric and MySQL connection configuration
50
"""
51
52
def connect(self, **config):
53
"""Establish connection through Fabric"""
54
55
def disconnect(self):
56
"""Disconnect from Fabric and MySQL servers"""
57
58
def is_connected(self):
59
"""Check if connection is active"""
60
61
def reset_cache(self):
62
"""Reset Fabric server group cache"""
63
64
def set_property(self, **properties):
65
"""Set connection properties"""
66
67
@property
68
def fabric(self):
69
"""Get Fabric interface object"""
70
71
@property
72
def group(self):
73
"""Current server group name"""
74
75
@property
76
def mode(self):
77
"""Current connection mode"""
78
```
79
80
**Usage Example:**
81
82
```python
83
import mysql.connector.fabric as fabric
84
85
# Basic Fabric connection
86
config = {
87
'fabric': {
88
'host': 'fabric-host.example.com',
89
'port': 32274,
90
'user': 'fabric_user',
91
'password': 'fabric_password'
92
},
93
'user': 'mysql_user',
94
'password': 'mysql_password',
95
'database': 'myapp',
96
'group': 'myapp_servers',
97
'mode': fabric.MODE_READWRITE
98
}
99
100
connection = fabric.connect(**config)
101
cursor = connection.cursor()
102
103
# Execute queries - Fabric handles server selection
104
cursor.execute("SELECT COUNT(*) FROM users")
105
result = cursor.fetchone()
106
print(f"User count: {result[0]}")
107
108
cursor.close()
109
connection.close()
110
```
111
112
### Fabric Interface
113
114
Direct interface to MySQL Fabric management system.
115
116
```python { .api }
117
class Fabric:
118
"""
119
Direct interface to MySQL Fabric management system.
120
121
Provides low-level access to Fabric services for server group
122
management, sharding operations, and high availability configuration.
123
"""
124
125
def __init__(self, host='localhost', port=32274, user='', password='', **kwargs):
126
"""
127
Initialize Fabric interface.
128
129
Parameters:
130
- host (str): Fabric server hostname
131
- port (int): Fabric server port (default: 32274)
132
- user (str): Fabric username
133
- password (str): Fabric password
134
- **kwargs: Additional connection parameters
135
"""
136
137
def connect(self):
138
"""Connect to Fabric server"""
139
140
def disconnect(self):
141
"""Disconnect from Fabric server"""
142
143
def is_connected(self):
144
"""Check if connected to Fabric"""
145
146
def get_group_servers(self, group_id, mode=None):
147
"""
148
Get servers in a group.
149
150
Parameters:
151
- group_id (str): Server group identifier
152
- mode (int): Connection mode filter
153
154
Returns:
155
list: Server information tuples
156
"""
157
158
def get_group_server(self, group_id, mode=MODE_READWRITE):
159
"""
160
Get primary server from group.
161
162
Parameters:
163
- group_id (str): Server group identifier
164
- mode (int): Connection mode
165
166
Returns:
167
tuple: Server information (host, port, weight, status)
168
"""
169
170
def report_error(self, server_uuid, error_code, error_message):
171
"""
172
Report server error to Fabric.
173
174
Parameters:
175
- server_uuid (str): Server UUID
176
- error_code (int): Error code
177
- error_message (str): Error description
178
"""
179
180
def report_failure(self, server_uuid):
181
"""
182
Report server failure to Fabric.
183
184
Parameters:
185
- server_uuid (str): Server UUID that failed
186
"""
187
188
def lookup_servers(self, tables, key=None, group=None, mode=MODE_READWRITE):
189
"""
190
Lookup servers for sharding key.
191
192
Parameters:
193
- tables (list): Table names for sharding
194
- key (str): Sharding key value
195
- group (str): Server group name
196
- mode (int): Connection mode
197
198
Returns:
199
list: Server information for sharding key
200
"""
201
202
def get_sharding_information(self, tables, scope=SCOPE_GLOBAL):
203
"""
204
Get sharding configuration information.
205
206
Parameters:
207
- tables (list): Table names
208
- scope (str): Sharding scope
209
210
Returns:
211
dict: Sharding configuration details
212
"""
213
214
# Sharding scope constants
215
SCOPE_GLOBAL = "GLOBAL"
216
SCOPE_LOCAL = "LOCAL"
217
```
218
219
### Sharding Support
220
221
Database sharding configuration and management through Fabric.
222
223
```python { .api }
224
def connect(group=None, key=None, tables=None, scope=SCOPE_GLOBAL, mode=MODE_READWRITE, **config):
225
"""
226
Connect with sharding support.
227
228
Parameters:
229
- group (str): Server group for non-sharded tables
230
- key (str): Sharding key value for routing
231
- tables (list): Tables involved in sharded operations
232
- scope (str): Sharding scope (GLOBAL or LOCAL)
233
- mode (int): Connection mode (readonly/readwrite)
234
- **config: Fabric and MySQL connection configuration
235
236
Returns:
237
MySQLFabricConnection: Sharding-aware connection
238
"""
239
```
240
241
**Usage Example:**
242
243
```python
244
import mysql.connector.fabric as fabric
245
246
# Sharded connection configuration
247
config = {
248
'fabric': {
249
'host': 'fabric.example.com',
250
'user': 'fabric_admin',
251
'password': 'fabric_secret'
252
},
253
'user': 'app_user',
254
'password': 'app_password',
255
'database': 'ecommerce'
256
}
257
258
# Connect for specific customer (sharding key)
259
customer_id = 12345
260
connection = fabric.connect(
261
key=str(customer_id),
262
tables=['orders', 'order_items', 'payments'],
263
mode=fabric.MODE_READWRITE,
264
**config
265
)
266
267
cursor = connection.cursor()
268
269
# Queries automatically routed to correct shard
270
cursor.execute(
271
"SELECT * FROM orders WHERE customer_id = %s",
272
(customer_id,)
273
)
274
orders = cursor.fetchall()
275
276
# Insert into sharded table
277
cursor.execute(
278
"INSERT INTO orders (customer_id, total) VALUES (%s, %s)",
279
(customer_id, 99.99)
280
)
281
connection.commit()
282
283
cursor.close()
284
connection.close()
285
```
286
287
### High Availability Configuration
288
289
Automatic failover and load balancing configuration.
290
291
```python { .api }
292
def connect(group=None, mode=MODE_READWRITE, attempts=3, attempt_delay=1, **config):
293
"""
294
Connect with high availability features.
295
296
Parameters:
297
- group (str): Server group name for HA
298
- mode (int): Connection mode for server selection
299
- attempts (int): Number of failover attempts
300
- attempt_delay (int): Delay between failover attempts
301
- **config: Connection configuration
302
303
Returns:
304
MySQLFabricConnection: HA-enabled connection
305
"""
306
307
class MySQLFabricConnection:
308
"""Connection with automatic failover support"""
309
310
def failover(self):
311
"""Trigger manual failover to backup server"""
312
313
def get_server_uuid(self):
314
"""Get UUID of currently connected server"""
315
316
def report_connection_error(self, error):
317
"""Report connection error for failover decision"""
318
```
319
320
**Usage Example:**
321
322
```python
323
import mysql.connector.fabric as fabric
324
325
# High availability configuration
326
ha_config = {
327
'fabric': {
328
'host': 'fabric-manager.example.com',
329
'user': 'ha_admin',
330
'password': 'ha_secret'
331
},
332
'user': 'app_user',
333
'password': 'app_password',
334
'database': 'production',
335
'group': 'production_masters',
336
'mode': fabric.MODE_READWRITE,
337
'attempts': 5,
338
'attempt_delay': 2
339
}
340
341
try:
342
connection = fabric.connect(**ha_config)
343
cursor = connection.cursor()
344
345
# Application queries with automatic failover
346
cursor.execute("SELECT COUNT(*) FROM active_sessions")
347
session_count = cursor.fetchone()[0]
348
349
print(f"Active sessions: {session_count}")
350
351
except fabric.DatabaseError as err:
352
print(f"Database error with failover: {err}")
353
354
finally:
355
if 'connection' in locals():
356
cursor.close()
357
connection.close()
358
359
# Read-only connections for reporting
360
readonly_config = ha_config.copy()
361
readonly_config.update({
362
'group': 'production_slaves',
363
'mode': fabric.MODE_READONLY
364
})
365
366
ro_connection = fabric.connect(**readonly_config)
367
ro_cursor = ro_connection.cursor()
368
369
# Read-only queries distributed across slaves
370
ro_cursor.execute("SELECT DATE(created_at), COUNT(*) FROM users GROUP BY DATE(created_at)")
371
daily_signups = ro_cursor.fetchall()
372
373
for date, count in daily_signups:
374
print(f"{date}: {count} signups")
375
376
ro_cursor.close()
377
ro_connection.close()
378
```
379
380
### Fabric Management
381
382
Administrative operations for Fabric server groups.
383
384
```python { .api }
385
class Fabric:
386
"""Administrative interface for Fabric management"""
387
388
def create_group(self, group_id, description=''):
389
"""
390
Create new server group.
391
392
Parameters:
393
- group_id (str): Unique group identifier
394
- description (str): Group description
395
"""
396
397
def destroy_group(self, group_id):
398
"""
399
Delete server group.
400
401
Parameters:
402
- group_id (str): Group identifier to delete
403
"""
404
405
def add_server(self, group_id, host, port, weight=1.0):
406
"""
407
Add server to group.
408
409
Parameters:
410
- group_id (str): Target group identifier
411
- host (str): MySQL server hostname
412
- port (int): MySQL server port
413
- weight (float): Server weight for load balancing
414
"""
415
416
def remove_server(self, server_uuid):
417
"""
418
Remove server from all groups.
419
420
Parameters:
421
- server_uuid (str): Server UUID to remove
422
"""
423
424
def promote_server(self, group_id, server_uuid):
425
"""
426
Promote server to master in group.
427
428
Parameters:
429
- group_id (str): Group identifier
430
- server_uuid (str): Server UUID to promote
431
"""
432
433
def set_server_weight(self, server_uuid, weight):
434
"""
435
Set server weight for load balancing.
436
437
Parameters:
438
- server_uuid (str): Server UUID
439
- weight (float): New weight value
440
"""
441
```
442
443
## Types
444
445
```python { .api }
446
FabricConfig = {
447
'fabric': {
448
'host': str,
449
'port': int,
450
'user': str,
451
'password': str,
452
'connection_timeout': int,
453
'connection_attempts': int,
454
'connection_delay': int
455
},
456
'group': str,
457
'key': str,
458
'tables': list[str],
459
'scope': str,
460
'mode': int,
461
'attempts': int,
462
'attempt_delay': int
463
}
464
465
ServerInfo = tuple[
466
str, # host
467
int, # port
468
float, # weight
469
str, # status
470
str # mode
471
]
472
473
ShardingInfo = {
474
'shard_id': int,
475
'group_id': str,
476
'global_group': str,
477
'state': str,
478
'sharding_type': str,
479
'sharding_key': str
480
}
481
```