/usr/lib/python2.7/dist-packages/mysql/fabric/services/server.py is in mysql-utilities 1.6.1-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 | #
# Copyright (c) 2013,2014, Oracle and/or its affiliates. All rights reserved.
#
# 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; version 2 of the License.
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""This module provides the necessary interfaces for performing administrative
tasks on groups and servers, specifically MySQL Servers.
It is possible to add, update and remove a group. One cannot, however, remove
a group if there are associated servers. It is possible to add a server to a
group and remove a server from a group. Search functions are also provided so
that one may look up groups and servers. Given a server's address, one may
also find out the server's uuid if the server is alive and kicking.
When a group is created though, it is inactive which means that the failure
detector will not check if its servers are alive. To start up the failure
detector, one needs to explicitly activate it per group. A server may have
one of the following statuses:
- PRIMARY - This is set when the server may accept both reads and writes
operations.
- SECONDARY - This is set when the server may accept only read operations.
- SPARE - This is set when users want to have server that is kept in sync
but does not accept neither reads or writes operations.
- FAULTY - This is set by the failure detector and indicates that a server
is not reachable.
Find in what follows the possible state transitions:
.. graphviz::
digraph state_transition {
rankdir=LR;
size="8,5"
node [shape = circle]; Primary;
node [shape = circle]; Secondary;
node [shape = circle]; Spare;
node [shape = circle]; Faulty;
Primary -> Secondary [ label = "demote" ];
Primary -> Faulty [ label = "failure" ];
Secondary -> Primary [ label = "promote" ];
Secondary -> Spare [ label = "set_status" ];
Secondary -> Faulty [ label = "failure" ];
Spare -> Primary [ label = "promote" ];
Spare -> Secondary [ label = "set_status" ];
Spare -> Faulty [ label = "failure" ];
Faulty -> Spare [ label = "set_status" ];
}
It is worth noticing that this module only provides functions for performing
basic administrative tasks, provisioning and high-availability functions are
provided elsewhere.
"""
import logging
import uuid as _uuid
import mysql.fabric.services.utils as _utils
from mysql.connector.errorcode import (
ER_ROW_IS_REFERENCED,
ER_ROW_IS_REFERENCED_2,
)
from mysql.fabric import (
backup as _backup,
events as _events,
server as _server,
errors as _errors,
failure_detector as _detector,
group_replication as _group_replication,
sharding as _sharding,
config as _config,
)
from mysql.fabric.command import (
ProcedureGroup,
Command,
ResultSet,
CommandResult,
)
from mysql.fabric.utils import (
get_time,
)
from mysql.fabric.connection import (
split_host_port,
)
_LOGGER = logging.getLogger(__name__)
SERVER_NOT_FOUND = "Server with UUID %s not found."
MYSQLDUMP_NOT_FOUND = "Unable to find MySQLDump in location %s"
MYSQLCLIENT_NOT_FOUND = "Unable to find MySQL Client in location %s"
MIN_UNREACHABLE_TIMEOUT = 1
MAX_UNREACHABLE_TIMEOUT = 60
DEFAULT_UNREACHABLE_TIMEOUT = 5
class GroupLookups(Command):
"""Return information on existing group(s).
"""
group_name = "group"
command_name = "lookup_groups"
def execute(self, group_id=None):
"""Return information on existing group(s).
:param group_id: None if one wants to list the existing groups or
group's id if one wants information on a group.
:return: List with {"group_id" : group_id, "failure_detector": ON/OFF,
"description" : description}.
"""
if group_id is None:
gids = _server.Group.groups()
else:
gids = [group_id]
_LOGGER.debug("Group IDs: %s", gids)
# Fetch all the groups before building the result set since an
# exception can be thrown and there is little point in trying
# to build a result set before all groups can be fetched.
groups = [ _retrieve_group(gid) for gid in gids ]
rset = ResultSet(
names=('group_id', 'description', 'failure_detector', 'master_uuid'),
types=(str, str, bool, str)
)
for group in groups:
rset.append_row([
group.group_id, # group_id
group.description, # description
group.status, # failure_detector
group.master, # master_uuid
])
return CommandResult(None, results=rset)
CREATE_GROUP = _events.Event()
class GroupCreate(ProcedureGroup):
"""Create a group.
"""
group_name = "group"
command_name = "create"
def execute(self, group_id, description=None, synchronous=True):
"""Create a group.
:param group_id: Group's id.
:param description: Group's description.
:param synchronous: Whether one should wait until the execution finishes
or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(
CREATE_GROUP, self.get_lockable_objects(), group_id, description
)
return self.wait_for_procedures(procedures, synchronous)
UPDATE_GROUP = _events.Event()
class GroupDescription(ProcedureGroup):
"""Update group's description.
"""
group_name = "group"
command_name = "description"
def execute(self, group_id, description=None, synchronous=True):
"""Update group's description.
:param group_id: Group's id.
:param description: Group's description.
:param synchronous: Whether one should wait until the execution finishes
or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(
UPDATE_GROUP, self.get_lockable_objects(), group_id, description
)
return self.wait_for_procedures(procedures, synchronous)
DESTROY_GROUP = _events.Event()
class DestroyGroup(ProcedureGroup):
"""Remove a group.
"""
group_name = "group"
command_name = "destroy"
def execute(self, group_id, synchronous=True):
"""Remove a group.
:param group_id: Group's id.
:param synchronous: Whether one should wait until the execution finishes
or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(
DESTROY_GROUP, self.get_lockable_objects(), group_id
)
return self.wait_for_procedures(procedures, synchronous)
class ServerLookups(Command):
"""Return information on existing server(s) in a group.
"""
group_name = "group"
command_name = "lookup_servers"
def execute(self, group_id, server_id=None, status=None, mode=None):
"""Return information on existing server(s) in a group.
:param group_id: Group's id.
:param uuid: None if one wants to list the existing servers
in a group or server's id if one wants information
on a server in a group.
:server_id type: Servers's UUID or HOST:PORT.
:param status: Server's status one is searching for.
:param mode: Server's mode one is searching for.
:return: Information on servers.
:rtype: List with [uuid, address, status, mode, weight]
"""
# Determine the set of servers to iterate through.
group = _retrieve_group(group_id)
if server_id is None:
servers = [server for server in group.servers()]
else:
servers = [_retrieve_server(server_id, group_id)]
# Determine the set of status to check upon.
if status is None:
status = _server.MySQLServer.SERVER_STATUS
else:
status = [_retrieve_server_status(status)]
# Determine the set of modes to check upon.
if mode is None:
mode = _server.MySQLServer.SERVER_MODE
else:
mode = [_retrieve_server_mode(mode)]
# Create result set.
rset = ResultSet(
names=('server_uuid', 'address', 'status', 'mode', 'weight'),
types=(str, str, str, str, float),
)
for server in servers:
if server.status in status and server.mode in mode:
rset.append_row([
str(server.uuid),
server.address,
server.status,
server.mode,
server.weight
])
return CommandResult(None, results=rset)
class ServerUuid(Command):
"""Return server's uuid.
"""
group_name = "server"
command_name = "lookup_uuid"
def execute(self, address, timeout=None):
"""Return server's UUID.
:param address: Server's address.
:param timeout: Time in seconds after which an error is reported
if the UUID is not retrieved.
:return: UUID.
"""
rset = ResultSet(names=['uuid'], types=[str])
rset.append_row([_lookup_uuid(address, timeout)])
return CommandResult(None, results=rset)
ADD_SERVER = _events.Event()
CONFIGURE_NEW_SERVER = _events.Event()
class ServerAdd(ProcedureGroup):
"""Add a server into group.
If users just want to update the state store and skip provisioning steps
such as configuring replication, the update_only parameter must be set to
true.
Note that the current implementation has a simple provisioning step that
makes the server point to the master if there is any.
"""
group_name = "group"
command_name = "add"
def execute(self, group_id, address, timeout=None, update_only=False,
synchronous=True):
"""Add a server into a group.
:param group_id: Group's id.
:param address: Server's address.
:param timeout: Time in seconds after which an error is reported
if one cannot access the server.
:update_only: Only update the state store and skip provisioning.
:param synchronous: Whether one should wait until the execution
finishes or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(ADD_SERVER, self.get_lockable_objects(),
group_id, address, timeout, update_only
)
return self.wait_for_procedures(procedures, synchronous)
REMOVE_SERVER = _events.Event()
class ServerRemove(ProcedureGroup):
"""Remove a server from a group.
"""
group_name = "group"
command_name = "remove"
def execute(self, group_id, server_id, synchronous=True):
"""Remove a server from a group.
:param group_id: Group's id.
:param server_id: Servers's UUID or HOST:PORT.
:param synchronous: Whether one should wait until the execution
finishes or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(REMOVE_SERVER, self.get_lockable_objects(),
group_id, server_id
)
return self.wait_for_procedures(procedures, synchronous)
ACTIVATE_GROUP = _events.Event()
class ActivateGroup(ProcedureGroup):
"""Activate failure detector for server(s) in a group.
By default the failure detector is disabled.
"""
group_name = "group"
command_name = "activate"
def execute(self, group_id, synchronous=True):
"""Activate a group.
:param group_id: Group's id.
:param synchronous: Whether one should wait until the execution
finishes or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(
ACTIVATE_GROUP, self.get_lockable_objects(), group_id
)
return self.wait_for_procedures(procedures, synchronous)
DEACTIVATE_GROUP = _events.Event()
class DeactivateGroup(ProcedureGroup):
"""Deactivate failure detector for server(s) in a group.
By default the failure detector is disabled.
"""
group_name = "group"
command_name = "deactivate"
def execute(self, group_id, synchronous=True):
"""Deactivate group.
:param group_id: Group's id.
:param synchronous: Whether one should wait until the execution
finishes or not.
:return: Tuple with job's uuid and status.
"""
procedures = _events.trigger(
DEACTIVATE_GROUP, self.get_lockable_objects(), group_id
)
return self.wait_for_procedures(procedures, synchronous)
class DumpServers(Command):
"""Return information about servers.
The servers might belong to any group that matches any of the provided
patterns, or all servers if no patterns are provided.
"""
group_name = "dump"
command_name = "servers"
def execute(self, connector_version=None, patterns=""):
"""Return information about all servers.
:param connector_version: The connectors version of the data.
:param patterns: group pattern.
"""
rset = ResultSet(
names=('server_uuid', 'group_id', 'host', 'port', 'mode', 'status', 'weight'),
types=(str, str, str, int, int, int, float)
)
for row in _server.MySQLServer.dump_servers(connector_version, patterns):
rset.append_row(row)
return CommandResult(None, results=rset)
SET_SERVER_STATUS = _events.Event()
class SetServerStatus(ProcedureGroup):
"""Set a server's status.
Any server added into a group has to be alive and kicking and its status
is automatically set to SECONDARY. If the failure detector is activate
and the server is not reachable, it is automatically set to FAULTY.
Users can also manually change the server's status. Usually, a user may
change a slave's mode to SPARE to avoid write and read access and
guarantee that it is not choosen when a failover or swithover routine is
executed.
By default replication is automatically configured when a server has its
status changed. In order to skip this, users must set the update_only
parameter to true. If done so, only the state store will be updated with
information on the new status.
"""
group_name = "server"
command_name = "set_status"
def execute(self, server_id, status, update_only=False, synchronous=True):
"""Set a server's status.
:param server_id: Servers's UUID or HOST:PORT.
:param status: Server's status.
:update_only: Only update the state store and skip provisioning.
:param synchronous: Whether one should wait until the execution
finishes or not.
"""
procedures = _events.trigger(
SET_SERVER_STATUS, self.get_lockable_objects(), server_id, status,
update_only
)
return self.wait_for_procedures(procedures, synchronous)
SET_SERVER_WEIGHT = _events.Event()
class SetServerWeight(ProcedureGroup):
"""Set a server's weight.
The weight determines the likelihood of a server being choseen by a
connector to process transactions. For example, a server whose weight
is 2.0 may receive 2 times more requests than a server whose weight is
1.0.
"""
group_name = "server"
command_name = "set_weight"
def execute(self, server_id, weight, synchronous=True):
"""Set a server's weight.
:param server_id: Servers's UUID or HOST:PORT.
:param weight: Server's weight.
:param synchronous: Whether one should wait until the execution
finishes or not.
"""
procedures = _events.trigger(
SET_SERVER_WEIGHT, self.get_lockable_objects(), server_id, weight
)
return self.wait_for_procedures(procedures, synchronous)
SET_SERVER_MODE = _events.Event()
CONFIGURE_FAULTY_SERVER = _events.Event()
class SetServerMode(ProcedureGroup):
"""Set a server's mode.
The mode determines whether a server can process read-only, read-write
or both transaction types.
"""
group_name = "server"
command_name = "set_mode"
def execute(self, server_id, mode, synchronous=True):
"""Set a server's mode.
:param server_id: Servers's UUID or HOST:PORT.
:param weight: Server's weight.
:param synchronous: Whether one should wait until the execution
finishes or not.
"""
procedures = _events.trigger(
SET_SERVER_MODE, self.get_lockable_objects(), server_id, mode
)
return self.wait_for_procedures(procedures, synchronous)
BACKUP_SERVER = _events.Event("BACKUP_SERVER")
RESTORE_SERVER = _events.Event("RESTORE_SERVER")
class CloneServer(ProcedureGroup):
"""Clone the objects of a given server into a destination server.
"""
group_name = "server"
command_name = "clone"
def execute(self, group_id, destn_address, server_id=None, timeout=None,
synchronous=True):
"""Clone the objects of a given server into a destination server.
:param group_id: The ID of the source group.
:param destn_address: The address of the destination MySQL Server.
:param source_id: The address or UUID of the source MySQL Server.
:param timeout: Time in seconds after which an error is reported
if the destination server is unreachable.
:param synchronous: Whether one should wait until the execution
finishes or not.
"""
# If the destination server is already part of a Fabric Group, raise
# an error
destn_server_uuid = _lookup_uuid(destn_address, timeout)
_check_server_not_in_any_group(destn_server_uuid)
host, port = split_host_port(
destn_address, _backup.MySQLDump.MYSQL_DEFAULT_PORT
)
# Fetch information on backup and restore programs.
config_file = self.config.config_file if self.config.config_file else ""
mysqldump_binary = _utils.read_config_value(
self.config,
'sharding',
'mysqldump_program'
)
mysqlclient_binary = _utils.read_config_value(
self.config,
'sharding',
'mysqlclient_program'
)
if not _utils.is_valid_binary(mysqldump_binary):
raise _errors.ServerError(MYSQLDUMP_NOT_FOUND % mysqldump_binary)
if not _utils.is_valid_binary(mysqlclient_binary):
raise _errors.ServerError(MYSQLCLIENT_NOT_FOUND % mysqlclient_binary)
# Fetch a reference to source server.
if server_id:
server = _retrieve_server(server_id, group_id)
else:
group = _retrieve_group(group_id)
server = _utils.fetch_backup_server(group)
# Schedule the clone operation through the executor.
procedures = _events.trigger(
BACKUP_SERVER,
self.get_lockable_objects(),
str(server.uuid),
host,
port,
mysqldump_binary,
mysqlclient_binary,
config_file
)
return self.wait_for_procedures(procedures, synchronous)
@_events.on_event(CREATE_GROUP)
def _create_group(group_id, description):
"""Create a group.
"""
_check_group_exists(group_id)
group = _server.Group(group_id=group_id, description=description,
status=_server.Group.INACTIVE)
_server.Group.add(group)
_LOGGER.debug("Added group (%s).", group)
@_events.on_event(ACTIVATE_GROUP)
def _activate_group(group_id):
"""Activate a group.
"""
group = _retrieve_group(group_id)
group.status = _server.Group.ACTIVE
_detector.FailureDetector.register_group(group_id)
_LOGGER.debug("Group (%s) is active.", group)
@_events.on_event(DEACTIVATE_GROUP)
def _deactivate_group(group_id):
"""Deactivate a group.
"""
group = _retrieve_group(group_id)
group.status = _server.Group.INACTIVE
_detector.FailureDetector.unregister_group(group_id)
_LOGGER.debug("Group (%s) is active.", str(group))
@_events.on_event(UPDATE_GROUP)
def _update_group_description(group_id, description):
"""Update a group description.
"""
group = _retrieve_group(group_id)
group.description = description
_LOGGER.debug("Updated group (%s).", group)
@_events.on_event(DESTROY_GROUP)
def _destroy_group(group_id):
"""Destroy a group.
"""
group = _retrieve_group(group_id)
_check_group_dependencies(group)
_detector.FailureDetector.unregister_group(group_id)
try:
_server.Group.remove(group)
except _errors.DatabaseError as error:
foreign_key_errors = (ER_ROW_IS_REFERENCED, ER_ROW_IS_REFERENCED_2)
if error.errno in foreign_key_errors:
raise _errors.GroupError(
"Cannot destroy group (%s): %s." % (group_id, error, )
)
raise
_LOGGER.debug("Destroyed group (%s).", group)
@_destroy_group.undo
def _undo_destroy_group(group_id):
"""Register a group if the destroy operation has failed.
"""
_detector.FailureDetector.register_group(group_id)
def _lookup_uuid(address, timeout):
"""Return server's uuid.
"""
try:
timeout = float(timeout)
except (TypeError, ValueError):
pass
timeout = timeout or DEFAULT_UNREACHABLE_TIMEOUT
try:
return _server.MySQLServer.discover_uuid(
address=address, connection_timeout=timeout
)
except _errors.DatabaseError as error:
raise _errors.ServerError(
"Error accessing server (%s): %s." % (address, error)
)
@_events.on_event(ADD_SERVER)
def _add_server(group_id, address, timeout, update_only):
"""Only add a server with a configuring status into a group.
The next step is responsible for setting up the server though.
For example, replication will be configured in the next step.
"""
group = _retrieve_group(group_id)
uuid = _lookup_uuid(address, timeout)
_check_server_exists(uuid)
server = _server.MySQLServer(uuid=_uuid.UUID(uuid), address=address)
# Add server to the state store.
_server.MySQLServer.add(server)
# Add server as a member in the group.
server.group_id = group_id
_events.trigger_within_procedure(
CONFIGURE_NEW_SERVER, group_id, str(server.uuid), update_only
)
@_events.on_event(CONFIGURE_NEW_SERVER)
def _configure_new_server(group_id, server_uuid, update_only):
"""Configure replication and set the server's status to secondary.
"""
group = _server.Group.fetch(group_id)
server = _server.MySQLServer.fetch(server_uuid)
server.status = _server.MySQLServer.SECONDARY
try:
_check_requirements(server)
if not update_only:
_configure_as_slave(group, server)
except (_errors.ServerError, _errors.DatabaseError):
server.disconnect()
raise
_LOGGER.debug("Added server (%s) to group (%s).", server, group)
@_events.on_event(REMOVE_SERVER)
def _remove_server(group_id, server_id):
"""Remove a server from a group.
"""
group = _retrieve_group(group_id)
server = _retrieve_server(server_id, group_id)
if group.master == server.uuid:
raise _errors.ServerError(
"Cannot remove server (%s), which is master in group (%s). "
"Please, demote it first." % (server.uuid, group_id)
)
_server.MySQLServer.remove(server)
server.disconnect()
@_events.on_event(SET_SERVER_STATUS)
def _set_server_status(server_id, status, update_only):
"""Set a server's status.
"""
status = _retrieve_server_status(status)
server = _retrieve_server(server_id)
if status == _server.MySQLServer.PRIMARY:
_set_server_status_primary(server, update_only)
elif status == _server.MySQLServer.FAULTY:
_set_server_status_faulty(server, update_only)
elif status == _server.MySQLServer.SECONDARY:
_set_server_status_secondary(server, update_only)
elif status == _server.MySQLServer.SPARE:
_set_server_status_spare(server, update_only)
def _retrieve_server_status(status):
"""Check whether the server's status is valid or not and
if an integer was provided retrieve the correspondent
string.
"""
valid = False
try:
idx = int(status)
try:
status = _server.MySQLServer.get_status(idx)
valid = True
except IndexError:
pass
except ValueError:
try:
status = str(status).upper()
_server.MySQLServer.get_status_idx(status)
valid = True
except ValueError:
pass
if not valid:
values = [ str((_server.MySQLServer.get_status_idx(value), value))
for value in _server.MySQLServer.SERVER_STATUS ]
raise _errors.ServerError("Trying to use an invalid status (%s). "
"Possible values are %s." % (status, ", ".join(values))
)
return status
def _set_server_status_primary(server, update_only):
"""Set server's status to primary.
"""
raise _errors.ServerError(
"If you want to make a server (%s) primary, please, use the "
"group.promote function." % (server.uuid, )
)
def _set_server_status_faulty(server, update_only):
raise _errors.ServerError(
"If you want to set a server (%s) to faulty, please, use the "
"threat.report_faulty interface." % (server.uuid, )
)
def _set_server_status_secondary(server, update_only):
"""Set server's status to secondary.
"""
allowed_status = [_server.MySQLServer.SPARE]
status = _server.MySQLServer.SECONDARY
mode = _server.MySQLServer.READ_ONLY
_do_set_status(server, allowed_status, status, mode, update_only)
def _set_server_status_spare(server, update_only):
"""Set server's status to spare. If the server has faulty or
configuring status, it might happen that it is not properly
configured. So the server's status is temporarily set to
configuring and the proper configuration actions are taken
in the next step.
"""
allowed_status = [
_server.MySQLServer.SECONDARY, _server.MySQLServer.FAULTY,
_server.MySQLServer.CONFIGURING
]
status = _server.MySQLServer.SPARE
mode = _server.MySQLServer.OFFLINE
previous_status = server.status
if previous_status in \
(_server.MySQLServer.FAULTY, _server.MySQLServer.CONFIGURING):
if server.is_alive():
_events.trigger_within_procedure(
CONFIGURE_FAULTY_SERVER, str(server.uuid), previous_status,
update_only
)
status = _server.MySQLServer.CONFIGURING
_do_set_status(server, allowed_status, status, mode, update_only)
@_events.on_event(CONFIGURE_FAULTY_SERVER)
def _configure_faulty_server(server_uuid, previous_status, update_only):
"""Configure replication and set the server's status to spare.
"""
server = _server.MySQLServer.fetch(server_uuid)
server.status = _server.MySQLServer.SPARE
try:
_check_requirements(server)
if not update_only:
group = _server.Group.fetch(server.group_id)
_configure_as_slave(group, server)
except (_errors.ServerError, _errors.DatabaseError):
server.disconnect()
raise
def _do_set_status(server, allowed_status, status, mode, update_only):
"""Set server's status.
"""
allowed_transition = server.status in allowed_status
previous_status = server.status
if allowed_transition:
server.status = status
server.mode = mode
else:
raise _errors.ServerError(
"Cannot change server's (%s) status from (%s) to (%s)." %
(str(server.uuid), server.status, status)
)
_LOGGER.debug(
"Changed server's status (%s) from (%s) to (%s). Update-only "
"state store parameter is (%s).", str(server.uuid), previous_status,
server.status, update_only
)
@_events.on_event(SET_SERVER_WEIGHT)
def _set_server_weight(server_id, weight):
"""Set server's weight.
"""
server = _retrieve_server(server_id)
try:
weight = float(weight)
except ValueError:
raise _errors.ServerError("Value (%s) must be a float." % (weight, ))
if weight <= 0.0:
raise _errors.ServerError(
"Cannot set the server's weight (%s) to a value lower "
"than or equal to 0.0" % (weight, )
)
server.weight = weight
@_events.on_event(SET_SERVER_MODE)
def _set_server_mode(server_id, mode):
"""Set server's mode.
"""
mode = _retrieve_server_mode(mode)
server = _retrieve_server(server_id)
if server.status == _server.MySQLServer.PRIMARY:
_set_server_mode_primary(server, mode)
elif server.status == _server.MySQLServer.SECONDARY:
_set_server_mode_secondary(server, mode)
elif server.status == _server.MySQLServer.SPARE:
_set_server_mode_spare(server, mode)
elif server.status == _server.MySQLServer.FAULTY:
_set_server_mode_faulty(server, mode)
@_events.on_event(BACKUP_SERVER)
def _backup_server(source_uuid, host, port, mysqldump_binary,
mysqlclient_binary, config_file):
"""Backup the source server, given by the source_uuid.
:param source_uuid: The UUID of the source server.
:param host: The hostname of the destination server.
:param port: The port number of the destination server.
:param mysqldump_binary: The MySQL Dump Binary path.
:param mysqlclient_binary: The MySQL Client Binary path.
:param config_file: The complete path to the fabric configuration
file.
"""
source_server = _server.MySQLServer.fetch(source_uuid)
#Do the backup of the group hosting the source shard.
backup_image = _backup.MySQLDump.backup(
source_server,
config_file,
mysqldump_binary
)
_LOGGER.debug("Done with backup of server with uuid = %s.", source_uuid)
procedures = _events.trigger_within_procedure(
RESTORE_SERVER,
source_uuid,
host,
port,
backup_image.path,
mysqlclient_binary,
config_file
)
@_events.on_event(RESTORE_SERVER)
def _restore_server(source_uuid, host, port, backup_image, mysqlclient_binary,
config_file):
"""Restore the backup on the destination Server.
:param source_uuid: The UUID of the source server.
:param host: The hostname of the destination server.
:param port: The port number of the destination server.
:param userid: The User Name to be used to connect to the destn server.
:param passwd: The password to be used to connect to the destn server.
:param mysqldump_binary: The MySQL Dump Binary path.
:param mysqlclient_binary: The MySQL Client Binary path.
:param config_file: The complete path to the fabric configuration
file.
"""
source_server = _server.MySQLServer.fetch(source_uuid)
if not source_server:
raise _errors.ServerError(SERVER_NOT_FOUND % source_uuid)
#Build a backup image that will be used for restoring
bk_img = _backup.BackupImage(backup_image)
_backup.MySQLDump.restore_server(
host,
port,
source_server.USER,
source_server.PASSWD,
bk_img,
config_file,
mysqlclient_binary
)
_LOGGER.debug("Done with restore of server with host = %s, port = %s" %\
(host, port,))
def _retrieve_server_mode(mode):
"""Check whether the server's mode is valid or not and if an integer was
provided retrieve the correspondent string.
"""
valid = False
try:
idx = int(mode)
try:
mode = _server.MySQLServer.get_mode(idx)
valid = True
except IndexError:
pass
except ValueError:
try:
mode = str(mode).upper()
_server.MySQLServer.get_mode_idx(mode)
valid = True
except ValueError:
pass
if not valid:
values = [ str((_server.MySQLServer.get_mode_idx(value), value))
for value in _server.MySQLServer.SERVER_MODE ]
raise _errors.ServerError("Trying to use an invalid mode (%s). "
"Possible values are: %s." % (mode, ", ".join(values))
)
return mode
def _set_server_mode_primary(server, mode):
"""Set server's mode when it is a primary.
"""
allowed_mode = \
(_server.MySQLServer.WRITE_ONLY, _server.MySQLServer.READ_WRITE)
_do_set_server_mode(server, mode, allowed_mode)
def _set_server_mode_secondary(server, mode):
"""Set server's mode when it is a secondary.
"""
allowed_mode = \
(_server.MySQLServer.OFFLINE, _server.MySQLServer.READ_ONLY)
_do_set_server_mode(server, mode, allowed_mode)
def _set_server_mode_spare(server, mode):
"""Set server's mode when it is a spare.
"""
allowed_mode = \
(_server.MySQLServer.OFFLINE, _server.MySQLServer.READ_ONLY)
_do_set_server_mode(server, mode, allowed_mode)
def _set_server_mode_faulty(server, mode):
"""Set server's mode when it is a faulty.
"""
allowed_mode = ()
_do_set_server_mode(server, mode, allowed_mode)
def _do_set_server_mode(server, mode, allowed_mode):
"""Set server's mode.
"""
if mode not in allowed_mode:
raise _errors.ServerError(
"Cannot set mode to (%s) when the server's (%s) status is (%s)."
% (mode, server.uuid, server.status)
)
server.mode = mode
def _retrieve_server(server_id, group_id=None):
"""Return a MySQLServer object from a UUID or a HOST:PORT.
"""
server = _server.MySQLServer.fetch(server_id)
if not server:
raise _errors.ServerError(
"Server (%s) does not exist." % (server_id, )
)
if not server.group_id:
raise _errors.GroupError(
"Server (%s) does not belong to a group." % (server_id, )
)
if group_id is not None and group_id != server.group_id:
raise _errors.GroupError(
"Group (%s) does not contain server (%s)." % (group_id, server_id)
)
return server
def _check_server_exists(server_id):
"""Check whether a MySQLServer instance exists or not.
:param server_id: The UUID or the host:port for the server.
"""
server = _server.MySQLServer.fetch(server_id)
if server:
raise _errors.ServerError("Server (%s) already exists." % (server_id, ))
def _check_server_not_in_any_group(server_id):
"""Check for both the presence of the server object and its associated
group. If the server belongs to a group an error is raised.
:param server_id: The UUID or the host:port for the server.
"""
server = _server.MySQLServer.fetch(server_id)
if server and server.group_id:
raise _errors.ServerError(
"Destination server (%s) is already part of group (%s)" %
(server.address, server.group_id)
)
def _retrieve_group(group_id):
"""Return a Group object from an identifier.
"""
group = _server.Group.fetch(group_id)
if not group:
raise _errors.GroupError("Group (%s) does not exist." % (group_id, ))
return group
def _check_group_exists(group_id):
"""Check whether a group exists or not.
"""
group = _server.Group.fetch(group_id)
if group:
raise _errors.GroupError("Group (%s) already exists." % (group_id, ))
def _check_group_dependencies(group):
"""Check whether there is a shard associated with the group.
"""
group_id = group.group_id
shard_id = _sharding.Shards.lookup_shard_id(group_id)
if shard_id:
raise _errors.GroupError(
"Cannot destroy a group (%s) which is associated to a shard (%s)." %
(group_id, shard_id)
)
shard_mapping_id = _sharding.ShardMapping.lookup_shard_mapping_id(group_id)
if shard_mapping_id:
raise _errors.GroupError(
"Cannot destroy a group (%s) which is used as a global group in a "
"shard definition (%s)." % (group_id, shard_mapping_id)
)
if group.servers():
raise _errors.GroupError(
"Cannot destroy a group (%s) which has associated servers." %
(group_id, )
)
def _check_requirements(server):
"""Check if the server fulfils some requirements.
"""
# Being able to connect to the server is the first requirement.
server.connect()
if not server.check_version_compat((5, 6, 8)):
raise _errors.ServerError(
"Server (%s) has an outdated version (%s). 5.6.8 or greater "
"is required." % (server.uuid, server.version)
)
if not server.has_required_privileges():
raise _errors.ServerError(
"User (%s) does not have appropriate privileges (%s) on server "
"(%s, %s)." % (server.user,
", ".join(_server.MySQLServer.ALL_PRIVILEGES),
server.address, server.uuid)
)
if not server.gtid_enabled or not server.binlog_enabled:
raise _errors.ServerError(
"Server (%s) does not have the binary log or gtid enabled."
% (server.uuid, )
)
def _configure_as_slave(group, server):
"""Configure the server as a slave.
"""
try:
if group.master:
master = _server.MySQLServer.fetch(group.master)
master.connect()
_utils.switch_master(server, master)
except _errors.DatabaseError as error:
msg = "Error trying to configure server ({0}) as slave: {1}.".format(
server.uuid, error)
_LOGGER.debug(msg)
raise _errors.ServerError(msg)
def configure(config):
"""Set configuration values.
"""
try:
timeout = int(config.get("servers", "unreachable_timeout"))
if timeout < MIN_UNREACHABLE_TIMEOUT:
_LOGGER.warning(
"Unreachable timeout cannot be lower than %s.",
MIN_UNREACHABLE_TIMEOUT
)
timeout = MIN_UNREACHABLE_TIMEOUT
if timeout > MAX_UNREACHABLE_TIMEOUT:
_LOGGER.warning(
"Unreachable timeout cannot be greater than %s.",
MAX_UNREACHABLE_TIMEOUT
)
timeout = MAX_UNREACHABLE_TIMEOUT
global DEFAULT_UNREACHABLE_TIMEOUT
DEFAULT_UNREACHABLE_TIMEOUT = timeout
except (_config.NoOptionError, _config.NoSectionError, ValueError):
pass
|