app.py 8.18 KB
Newer Older
Aurel's avatar
Aurel committed
1 2
#
# Copyright (C) 2006-2009  Nexedi SA
3
#
Aurel's avatar
Aurel committed
4 5 6 7
# 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; either version 2
# of the License, or (at your option) any later version.
8
#
Aurel's avatar
Aurel committed
9 10 11 12 13 14 15 16 17 18 19
# 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 Street, Fifth Floor, Boston, MA  02110-1301, USA.

import logging

20
from neo.protocol import node_types, node_states
Aurel's avatar
Aurel committed
21
from neo.event import EventManager
22
from neo.connection import ClientConnection
Aurel's avatar
Aurel committed
23 24
from neo.neoctl.handler import CommandEventHandler
from neo.connector import getConnectorHandler
25
from neo.util import bin
Aurel's avatar
Aurel committed
26 27
from neo import protocol

28 29
class ActionError(Exception): 
    pass
30 31 32

def addAction(options):
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
33
      Change node state from "pending" to "running".
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
      Parameters:
      node uuid
        UUID of node to add, or "all".
    """
    if len(options) == 1 and options[0] == 'all':
        uuid_list = []
    else:
        uuid_list = [bin(opt) for opt in options]
    return protocol.addPendingNodes(uuid_list)

def setClusterAction(options):
    """
      Set cluster of given name to given state.
      Parameters:
      cluster state
        State to put the cluster in.
    """
    # XXX: why do we ask for a cluster name ?
    # We connect to only one cluster that we get from configuration file,
    # anyway.
    name, state = options
    state = protocol.cluster_states.getFromStr(state)
    if state is None:
        raise ActionError('unknown cluster state')
    return protocol.setClusterState(name, state)

def setNodeAction(options):
    """
      Put given node into given state.
      Parameters:
      node uuid
        UUID of target node
      node state
        Node state to set.
      change partition table (optional)
        If given with a 1 value, allow partition table to be changed.
    """
    uuid = bin(options.pop(0))
72 73
    state = options.pop(0) + '_STATE'
    state = node_states.getFromStr(state)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    if state is None:
        raise ActionError('unknown state type')
    if len(options):
        modify = int(options.pop(0))
    else:
        modify = 0
    return protocol.setNodeState(uuid, state, modify)

def printClusterAction(options):
    """
      Print cluster state.
    """
    return protocol.askClusterState()

def printNodeAction(options):
    """
      Print nodes of a given type.
      Parameters:
      node type
        Print known nodes of given type.
    """
95 96
    node_type = options.pop(0) + '_NODE_TYPE'
    node_type = node_types.getFromStr(node_type)
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
    if node_type is None:
        raise ActionError('unknown node type')
    return protocol.askNodeList(node_type)

def printPTAction(options):
    """
      Print the partition table.
      Parameters:
      range
        all   Prints the entire partition table.
        1 10  Prints rows 1 to 10 of partition table.
        10 0  Prints rows from 10 to the end of partition table.
      node uuid (optional)
        If given, prints only the rows in which given node is used.
    """
    offset = options.pop(0)
    if offset == "all":
        min_offset = 0
        max_offset = 0
    else:
        min_offset = int(offset)
        max_offset = int(options.pop(0))
    if len(options):
        uuid = bin(options.pop(0))
    else:
122
        uuid = None
123 124
    return protocol.askPartitionList(min_offset, max_offset, uuid)

125 126
def startCluster(options):
    """ 
127 128
    Allow it to leave the recovery stage and accept the current partition 
    table, or make an empty if nothing was found.
129 130 131 132 133
    Parameter: Cluster name
    """
    name = options.pop(0)
    return protocol.setClusterState(name, protocol.VERIFYING)

134 135 136 137 138 139 140 141
def dropNode(options):
    """
    Drop one or more storage node from the partition table. Its content 
    is definitely lost. Be carefull because currently there is no check 
    about the cluster operational status, so you can drop a node with 
    non-replicated data.
    Parameter: UUID
    """
142 143
    uuid = bin(options.pop(0))
    return protocol.setNodeState(uuid, protocol.DOWN_STATE, 1)
144 145


146 147 148 149 150 151 152 153 154 155
action_dict = {
    'print': {
        'pt': printPTAction,
        'node': printNodeAction,
        'cluster': printClusterAction,
    },
    'set': {
        'node': setNodeAction,
        'cluster': setClusterAction,
    },
156 157
    'start': {
        'cluster': startCluster,
158 159 160
    },
    'add': addAction,
    'drop': dropNode,
161 162
}

Aurel's avatar
Aurel committed
163 164 165
class Application(object):
    """The storage node application."""

166 167
    conn = None

Aurel's avatar
Aurel committed
168 169 170 171 172
    def __init__(self, ip, port, handler):

        self.connector_handler = getConnectorHandler(handler)
        self.server = (ip, port)
        self.em = EventManager()
173
        self.ptid = None
174
        self.trying_admin_node = False
Aurel's avatar
Aurel committed
175

176 177 178 179
    def getConnection(self):
        if self.conn is None:
            handler = CommandEventHandler(self)
            # connect to admin node
180
            self.trying_admin_node = True
181
            conn = None
182
            while self.trying_admin_node:
183 184 185
                self.em.poll(1)
                if conn is None:
                    self.trying_admin_node = True
186
                    logging.debug('connecting to address %s:%d', *(self.server))
187 188 189 190 191 192 193 194 195
                    conn = ClientConnection(self.em, handler, \
                                            addr = self.server,
                                            connector_handler = self.connector_handler)
            self.conn = conn
        return self.conn

    def doAction(self, packet):
        conn = self.getConnection()

196
        conn.ask(packet)
197 198 199 200 201 202 203
        self.result = ""
        while 1:
            self.em.poll(1)
            if len(self.result):
                break

    def __del__(self):
204 205
        if self.conn is not None:
            self.conn.close()
206

207
    def execute(self, args):
Aurel's avatar
Aurel committed
208 209
        """Execute the command given."""
        # print node type : print list of node of the given type (STORAGE_NODE_TYPE, MASTER_NODE_TYPE...)
210 211 212
        # set node uuid state [1|0] : set the node for the given uuid to the state (RUNNING_STATE, DOWN_STATE...)
        #                             and modify the partition if asked
        # set cluster name [shutdown|operational] : either shutdown the cluster or mark it as operational
213
        current_action = action_dict
214
        level = 0
215 216 217 218 219 220 221 222 223 224
        while current_action is not None and \
              level < len(args) and \
              isinstance(current_action, dict):
            current_action = current_action.get(args[level])
            level += 1
        if callable(current_action):
            try:
                p = current_action(args[level:])
            except ActionError, message:
                self.result = message
Aurel's avatar
Aurel committed
225
            else:
226
                self.doAction(p)
Aurel's avatar
Aurel committed
227
        else:
228 229
            self.result = usage('unknown command')

Aurel's avatar
Aurel committed
230
        return self.result
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

def _usage(action_dict, level=0):
    result = []
    append = result.append
    sub_level = level + 1
    for name, action in action_dict.iteritems():
        append('%s%s' % ('  ' * level, name))
        if isinstance(action, dict):
            append(_usage(action, level=sub_level))
        else:
            docstring_line_list = getattr(action, '__doc__',
                                          '(no docstring)').split('\n')
            # Strip empty lines at begining & end of line list
            for end in (0, -1):
                while len(docstring_line_list) \
                      and docstring_line_list[end] == '':
                    docstring_line_list.pop(end)
            # Get the indentation of first line, to preserve other lines
            # relative indentation.
            first_line = docstring_line_list[0]
            base_indentation = len(first_line) - len(first_line.lstrip())
            result.extend([('  ' * sub_level) + x[base_indentation:] \
                           for x in docstring_line_list])
    return '\n'.join(result)

def usage(message):
    output_list = [message, 'Available commands:', _usage(action_dict)]
    return '\n'.join(output_list)