dtr_utils.py 17.6 KB
Newer Older
Alan Taylor's avatar
Alan Taylor committed
1 2 3 4 5 6
"""
utilities

callable functions from this file:

    block_render_filename
7
    despatch_order
Alan Taylor's avatar
Alan Taylor committed
8 9 10 11 12
    no_dupes_ipu
    package_filename_for_cygwin
    render_block_normal

------------------------------------------------------------------------------
Alan Taylor's avatar
Alan Taylor committed
13
Copyright 2015-2017 Alan Taylor
Alan Taylor's avatar
Alan Taylor committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

This file is part of dtr.

dtr 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 3 of the License, or
(at your option) any later version.

dtr 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 dtr.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------
"""

32 33 34 35 36 37
import concurrent.futures as cf # ThreadPoolExecutor
import math                     # hypot
import multiprocessing as mp    # cpu_count, Queue
import socket                   # AF_INET, SOCK_STREAM, socket
import subprocess               # PIPE, Popen
import sys                      # exit
Alan Taylor's avatar
Alan Taylor committed
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


##############################################################################
# general support functions
##############################################################################

def _axis_bounds(blocks, block_roc):
    """
    returns the single axis minimum and maximum bounds for a given block in
    the range of 0 to 1

    no attempt is made to manually align to pixel boundaries or centres,
    Blender seems happiest with this arrangement

    for example, x-axis values for block 7 would be called as
    _axis_bounds(4, 2) from render_block_normal(), where 4 is the number of
    blocks in the axis, and 2 is the block column number (starting at zero),
    and would return (0.5, 0.75)

    +---+---+---+---+
    | 5 | 6 |>7<| 8 |
    +---+---+---+---+
    | 1 | 2 | 3 | 4 |
    +---+---+---+---+
            ^   ^
            |   |
          0.5   0.75

    --------------------------------------------------------------------------
    args
        blocks : int
            the number of blocks on the axis being considered
        block_roc : int
            block (r)ow (o)r (c)olumn
            block position on the axis being considered
    --------------------------------------------------------------------------
    returns
        tuple (float, float)
            lower and upper bounds of block in one axis
    --------------------------------------------------------------------------
    """
    lower_limit = block_roc / blocks
    upper_limit = (block_roc + 1) / blocks
    return (lower_limit, upper_limit)

def render_block_normal(settings, block_number):
    """
    return bottom left (x, y) and top right (x, y) of a given block number
    where values of x and y are between 0 and 1
    assume block 0 is bottom left, and block n (max value) is top right
    compute row and column of given block number

    --------------------------------------------------------------------------
    args
        settings : image_config dictionary
            contains core information about the image to be rendered
        block_number : int
            block number to be rendered
            e.g. for a render with 8 blocks, blocks would be numbered
            {1, 2, 3, 4, 5, 6, 7, 8}
    --------------------------------------------------------------------------
    returns
        tuple (float, float, float, float)
            lower and upper bounds of the given block in both axes
    --------------------------------------------------------------------------
    """
    block_row, block_col = divmod(block_number - 1, settings['blocks_x'])
    x_min, x_max = _axis_bounds(settings['blocks_x'], block_col)
    y_min, y_max = _axis_bounds(settings['blocks_y'], block_row)

    return (x_min, y_min, x_max, y_max)

110
def _dist_from_centre(settings, block_number):
Alan Taylor's avatar
Alan Taylor committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    """
    return the distance between the centre of the image and the
    centre of the block number given, respecting the aspect ratio of the
    image

    --------------------------------------------------------------------------
    args
        settings : image_config dictionary
            contains core information about the image to be rendered
        block_number : int
            block number to be rendered
    --------------------------------------------------------------------------
    returns
        float
            the block's distance from the centre of the image
    --------------------------------------------------------------------------
    """
    x_min, y_min, x_max, y_max = render_block_normal(settings, block_number)
    block_centre_x = (x_max + x_min) / 2.0
    block_centre_y = (y_max + y_min) / 2.0
    dxc = (0.5 - block_centre_x) * (settings['image_x'] / settings['image_y'])
    dyc = 0.5 - block_centre_y

134
    return math.hypot(dxc, dyc)
Alan Taylor's avatar
Alan Taylor committed
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

def no_dupes_ipu(original):
    """
    generic function that removes duplicate items from a list (i)n (p)lace;
    works for (u)n/hashable items

    specifically intended to work with a list of RenderNode instances,
    in case the user mistakenly listed ip addresses more than once
    in the configuration file

    --------------------------------------------------------------------------
    args
        original : list
    --------------------------------------------------------------------------
    returns
        original : list
            mutable type amended in place, no explicit return
    --------------------------------------------------------------------------
    """
    for j in original:
        ndup = original.count(j)
        o_ind = len(original) - 1
        while ndup > 1:
            if original[o_ind] == j:
                del original[o_ind]
                ndup -= 1
            o_ind -= 1

def package_filename_for_cygwin(node_op_sys, nix_filename):
    """
    Windows applications will expect to receive Windows filenames
    use Cygwin's cygpath() to perform the conversion

    --------------------------------------------------------------------------
    args
        node_op_sys : string
            the operating system for this render node, as given by uname
        nix_filename : string
            the standard filename, suitable for *nix type filesystems
    --------------------------------------------------------------------------
    returns
        string
            *nix or Cygwin-wrapped filename as appropriate
    --------------------------------------------------------------------------
    """
    if 'CYGWIN' not in node_op_sys:
        return nix_filename
    else:
        return '\"$(cygpath -aw \"' + nix_filename + '\")\"'

def block_render_filename(settings, block):
    """
    return a filename given the block number and seed

    --------------------------------------------------------------------------
    args
        settings : image_config dictionary
            contains core information about the image to be rendered
        block : int
            block number to be rendered
    --------------------------------------------------------------------------
    returns
        string
            filename for the rendered block image output
    --------------------------------------------------------------------------
    """
    return 'block_' + str(block).zfill(len(str(settings['blocks_required']))) + \
           '_seed_' + str(settings['seed']) + '.png'

def _node_alive(r_node):
    """
    establish whether the node is up by attempting to connect to port 22,
    as this port is typically used for ssh connections which this script
    uses heavily. a timeout period of 2 seconds is used.

    in essence we are looking to check the node is awake without having to
    handle the platform dependent nature of ping, such as differing
    return codes and command line options
    --------------------------------------------------------------------------
    args
        r_node : instance of RenderNode
            contains information about the node we are checking
    --------------------------------------------------------------------------
    returns
        bool
            True if node is up, False otherwise
    --------------------------------------------------------------------------
    """
    skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    skt.settimeout(2)

    try:
        skt.connect((r_node.ip_address, 22))
    except OSError:
        # connection failed
        alive = False
    else:
        # connection successful
        alive = True
    finally:
        skt.close()

    return alive

def _modern_blender_executable(node, test_blender):
    """
    detect whether the located Blender binary can be run, and whether it is
    a new enough version to be used

    The minimum Blender version deemed to be usable is 2.65 (released in 2012)
    as this release added the ability to manually set the tile size, which
    this script relies upon.
    --------------------------------------------------------------------------
    args
        node : RenderNode instance
            holds data for this render node
        test_blender : string
            command such as 'blender -v' to give verbose output
            so we can obtain the software version
    --------------------------------------------------------------------------
    returns
        bool
            True if Blender can be run, and is a new enough version
            False if Blender cannot be run, or is an old unsupported version
    --------------------------------------------------------------------------
    """
    response = _remote_command(node, test_blender)
    if 'Blender' not in response:
        return False

    b_vers = response.split()[1]
    if float(b_vers) < 2.65:
        print(node.ip_address, 'Blender version (' + b_vers.ljust(4) + \
            ') is too old to support the required feature set')
        return False

    return True

def _locate_blender(rni):
    """
    find the location of the Blender binary on the remote render node
    and perform a simple test to see if it can be executed

    --------------------------------------------------------------------------
    args
        rni : RenderNode instance
            (r)ender (n)ode (i)nstance - holds data for this render node
    --------------------------------------------------------------------------
    returns : string containing path or None (if binary not found)
    --------------------------------------------------------------------------
    """
    # see if we can find the binary with 'which'
    find_response = _remote_command(rni, 'which blender')
    if 'blender' in find_response:
        # binary found, now test to see if we can run it
        test_blender = 'blender -v'
        if _modern_blender_executable(rni, test_blender):
            return 'blender'

    # see if we can find the binary in ~
    blender_binloc = {
        'Darwin': '~/Blender/blender.app/Contents/MacOS/blender',
        'Linux': '~/Blender/blender',
        'CYGWIN' : '~/Blender/blender.exe'}
    b_loc = blender_binloc.get(rni.os, '~/Blender/blender.exe')
    find_blender = 'if [ ! -f ' + b_loc +  ' ]; then echo "MISSING"; fi'
    find_response = _remote_command(rni, find_blender)
    if 'MISSING' not in find_response:
        # binary found, now test to see if we can run it
        test_blender = b_loc + ' -v'
        if _modern_blender_executable(rni, test_blender):
            return b_loc
        else:
            return ''

    # Blender was either not found or not operational
    print(rni.ip_address + ' is up, but Blender was not found, or could not be executed')
    return ''

def _remote_command(node, execute_command):
    """
    execute command on remote node, wait for completion, then return stdout
    response

319 320 321
    Popen.communicate() is used here to make sure the command has fully
    completed before trying to read stdout

Alan Taylor's avatar
Alan Taylor committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    --------------------------------------------------------------------------
    args
        remote_ip : string
            ip address of remote node
        execute_command : string
            command to execute
    --------------------------------------------------------------------------
    returns : string containing stdout response from command
    --------------------------------------------------------------------------
    """
    on_this_node = node.username + '@' + node.ip_address
    remcom = subprocess.Popen(['ssh', on_this_node, execute_command], shell=False, \
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdo, _) = remcom.communicate(None, None)

    return stdo.decode('utf-8', 'ignore').rstrip()

339
def _check_node(node):
Alan Taylor's avatar
Alan Taylor committed
340 341 342 343 344 345
    """
    determine whether the node is up with a basic connection check,
    only then if we get a reply should we try to run a test command using ssh
    this should help control ssh's sometimes unpredictable behaviour when
    nodes are down

346 347 348 349 350 351
    --------------------------------------------------------------------------
    args
        node : RenderNode instance
            contains information about a single node
    --------------------------------------------------------------------------
    returns
352 353 354 355 356
        tuple x, y, z
            where:
            x = RenderNode instance, the node being checked
            y = boolean, whether the node is up
            z = string, Blender binary filename
357 358 359 360
    --------------------------------------------------------------------------
    """
    node_up = True
    binloc = ''
Alan Taylor's avatar
Alan Taylor committed
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
    if _node_alive(node):

        # node appears to be up and responsive (check 1 passed)
        uname_response = _remote_command(node, 'uname')
        if uname_response:

            # successfully ran a command over ssh (check 2 passed)
            node.os = 'CYGWIN' if 'CYGWIN' in uname_response else uname_response
            blender_location = _locate_blender(node)
            if blender_location:

                # Blender binary found and is operational (check 3 passed)
                binloc = blender_location
            else:
                # node is up, but appears to be misconfigured
                node_up = False
        else:
            # node appears to be misconfigured
            node_up = False
            print(node.ip_address + ' is up, but did not respond to a command sent via ssh')
    else:
        # the node may have simply gone to sleep, but it could be
        # misconfigured. as we can't tell whether it is misconfigured
        # or not, we must remove the node
        node_up = False
        print(node.ip_address + ' is down')

389
    return node, node_up, binloc
390 391 392

def remove_dead_nodes(available_nodes):
    """
393 394 395 396
    determine whether the node is up with a basic connection check,
    only then if we get a reply should we try to run a test command using ssh
    this should help control ssh's sometimes unpredictable behaviour when
    nodes are down
Alan Taylor's avatar
Alan Taylor committed
397

398 399 400 401 402
    with regard to the default value of max_workers for
    concurrent.futures.ThreadPoolExecutor:
    set the value of max_workers manually to make sure we get the
    latest Python behaviour when using Python 3.4

Alan Taylor's avatar
Alan Taylor committed
403 404 405 406 407 408 409 410 411 412
    --------------------------------------------------------------------------
    args
        available_nodes : list of RenderNode instances
            contains information about all the nodes in the cluster
    --------------------------------------------------------------------------
    returns
        available_nodes : list of RenderNode instances
            mutable type amended in place, no explicit return
    --------------------------------------------------------------------------
    """
413
    # run tests and process results
414
    try:
415
        num_threads = mp.cpu_count() * 5
416
    except NotImplementedError:
417
        num_threads = 5
418

419
    with cf.ThreadPoolExecutor(max_workers=num_threads) as executor:
420 421
        node_status = {executor.submit(_check_node, anode): anode for anode in available_nodes}
        for status in cf.as_completed(node_status):
422
            node, node_up, binloc = status.result()
423
            if node_up:
424
                node.binloc = binloc
425 426
            else:
                available_nodes.remove(node)
Alan Taylor's avatar
Alan Taylor committed
427 428 429 430 431

    # if no nodes are up, there is no point continuing
    if not available_nodes:
        print('exiting, as none of the given render nodes appear to be responsive')
        sys.exit()
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451


##############################################################################
# set the order that blocks are despatched to be rendered
##############################################################################

def _do_bottom_to_top(ic_settings, blocks):
    """
    bottom to top, with blocks running from left to right

    provides a service to despatch_order()
    """
    blocks.sort(reverse=True)

def _do_centre(ic_settings, blocks):
    """
    from centre outwards

    provides a service to despatch_order()
    """
452
    blocks.sort(key=lambda x: _dist_from_centre(ic_settings, x), reverse=True)
453 454 455 456 457 458 459

def despatch_order(ic_settings, blocks):
    """
    set the order that blocks are despatched to be rendered

    --------------------------------------------------------------------------
    args
Alan Taylor's avatar
Alan Taylor committed
460
        ic_settings : image_config dictionary
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
            contains core information about the image to be rendered
        blocks : list of unique ints
            all the blocks that need be rendered
    --------------------------------------------------------------------------
    returns
        blocks : list of unique ints
            mutable type amended in place, no explicit return
    --------------------------------------------------------------------------
    """
    check_setting = {
        'CENTRE': _do_centre,
        'BOTTOM_TO_TOP': _do_bottom_to_top
    }

    check_setting[ic_settings['render_order']](ic_settings, blocks)