This file is indexed.

/usr/share/pyshared/crm/utils.py is in pacemaker 1.1.7-1.

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
# Copyright (C) 2008 Dejan Muhamedagic <dmuhamedagic@suse.de>
# 
# 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.
# 
# This software 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 library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

import os
import pwd
from tempfile import mkstemp
import subprocess
import re
import glob
import time

from userprefs import Options, UserPrefs
from vars import Vars
from msg import *

def is_program(prog):
    return subprocess.call("which %s >/dev/null 2>&1"%prog, shell=True) == 0

def ask(msg):
    # if there's no terminal, no use asking and default to "no"
    if not sys.stdin.isatty():
        return False
    print_msg = True
    while True:
        try:
            ans = raw_input(msg + ' ')
        except EOFError:
            ans = 'n'
        if not ans or ans[0].lower() not in ('n','y'):
            if print_msg:
                print "Please answer with y[es] or n[o]"
                print_msg = False
        else:
            return ans[0].lower() == 'y'

def verify_boolean(opt):
    return opt.lower() in ("yes","true","on") or \
        opt.lower() in ("no","false","off")
def is_boolean_true(opt):
    return opt.lower() in ("yes","true","on")

def keyword_cmp(string1, string2):
    return string1.lower() == string2.lower()

from UserDict import DictMixin
class odict(DictMixin):
    def __init__(self, data=None, **kwdata):
        self._keys = []
        self._data = {}
    def __setitem__(self, key, value):
        if key not in self._data:
            self._keys.append(key)
        self._data[key] = value
    def __getitem__(self, key):
        if key not in self._data:
            return self._data[key.lower()]
        return self._data[key]
    def __delitem__(self, key):
        del self._data[key]
        self._keys.remove(key)
    def keys(self):
        return list(self._keys)
    def copy(self):
        copyDict = odict()
        copyDict._data = self._data.copy()
        copyDict._keys = self._keys[:]
        return copyDict

class olist(list):
    def __init__(self, keys):
        #print "Init %s" % (repr(keys))
        super(olist, self).__init__()
        for key in keys:
            self.append(key)
            self.append(key.upper())

def setup_help_aliases(obj):
    for cmd in obj.cmd_aliases.keys():
        for alias in obj.cmd_aliases[cmd]:
            if obj.help_table:
                obj.help_table[alias] = obj.help_table[cmd]
def setup_aliases(obj):
    for cmd in obj.cmd_aliases.keys():
        for alias in obj.cmd_aliases[cmd]:
            obj.cmd_table[alias] = obj.cmd_table[cmd]

def os_types_list(path):
    l = []
    for f in glob.glob(path):
        if os.access(f,os.X_OK) and os.path.isfile(f):
            a = f.split("/")
            l.append(a[-1])
    return l

def listtemplates():
    l = []
    for f in os.listdir(vars.tmpl_dir):
        if os.path.isfile("%s/%s" % (vars.tmpl_dir,f)):
            l.append(f)
    return l
def listconfigs():
    l = []
    for f in os.listdir(vars.tmpl_conf_dir):
        if os.path.isfile("%s/%s" % (vars.tmpl_conf_dir,f)):
            l.append(f)
    return l

def add_sudo(cmd):
    if user_prefs.crm_user:
        return "sudo -E -u %s %s"%(user_prefs.crm_user,cmd)
    return cmd
def pipe_string(cmd,s):
    rc = -1 # command failed
    cmd = add_sudo(cmd)
    p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
    try:
        p.communicate(s)
        p.wait()
        rc = p.returncode
    except IOError, msg:
        if not ("Broken pipe" in msg):
            common_err(msg)
    return rc
def filter_string(cmd,s,stderr_on = True):
    rc = -1 # command failed
    if stderr_on:
        stderr = None
    else:
        stderr = subprocess.PIPE
    cmd = add_sudo(cmd)
    p = subprocess.Popen(cmd, shell=True, \
        stdin = subprocess.PIPE, \
        stdout = subprocess.PIPE, stderr = stderr)
    try:
        outp = p.communicate(s)[0]
        p.wait()
        rc = p.returncode
    except IOError, msg:
        common_err(msg)
    return rc,outp

def str2tmp(s):
    '''
    Write the given string to a temporary file. Return the name
    of the file.
    '''
    fd,tmp = mkstemp()
    try: f = os.fdopen(fd,"w")
    except IOError, msg:
        common_err(msg)
        return
    f.write(s)
    f.close()
    return tmp
def str2file(s,fname):
    '''
    Write a string to a file.
    '''
    try: f = open(fname,"w")
    except IOError, msg:
        common_err(msg)
        return False
    f.write(s)
    f.close()
    return True

def is_filename_sane(name):
    if re.search("['`/#*?$\[\]]",name):
        common_err("%s: bad name"%name)
        return False
    return True
def is_name_sane(name):
    if re.search("[']",name):
        common_err("%s: bad name"%name)
        return False
    return True
def is_value_sane(name):
    if re.search("[']",name):
        common_err("%s: bad name"%name)
        return False
    return True

def show_dot_graph(dotfile):
    p = subprocess.Popen("%s %s" % (user_prefs.dotty,dotfile), shell=True, bufsize=0, stdin=None, stdout=None, stderr=None, close_fds=True)
    common_info("starting %s to show transition graph"%user_prefs.dotty)

def ext_cmd(cmd):
    if options.regression_tests:
        print ".EXT", cmd
    return subprocess.call(add_sudo(cmd), shell=True)

def get_stdout(cmd, stderr_on = True):
    '''
    Run a cmd, return stdin output.
    stderr_on controls whether to show output which comes on stderr.
    '''
    if stderr_on:
        stderr = None
    else:
        stderr = subprocess.PIPE
    proc = subprocess.Popen(cmd, shell = True, \
        stdout = subprocess.PIPE, stderr = stderr)
    outp = proc.communicate()[0]
    proc.wait()
    outp = outp.strip()
    return outp
def stdout2list(cmd, stderr_on = True):
    '''
    Run a cmd, fetch output, return it as a list of lines.
    stderr_on controls whether to show output which comes on stderr.
    '''
    s = get_stdout(add_sudo(cmd), stderr_on)
    return s.split('\n')

def wait4dc(what = "", show_progress = True):
    '''
    Wait for the DC to get into the S_IDLE state. This should be
    invoked only after a CIB modification which would exercise
    the PE. Parameter "what" is whatever the caller wants to be
    printed if showing progress.

    It is assumed that the DC is already in a different state,
    usually it should be either PENGINE or TRANSITION. This
    assumption may not be true, but there's a high chance that it
    is since crmd should be faster to move through states than
    this shell.

    Further, it may also be that crmd already calculated the new
    graph, did transition, and went back to the idle state. This
    may in particular be the case if the transition turned out to
    be empty.

    Tricky. Though in practice it shouldn't be an issue.

    There's no timeout, as we expect the DC to eventually becomes
    idle.
    '''
    cmd = "crmadmin -D"
    s = get_stdout(add_sudo(cmd))
    if not s.startswith("Designated"):
        common_warn("%s unexpected output: %s" % (cmd,s))
        return False
    dc = s.split()[-1]
    if not dc:
        common_warn("can't find DC in: %s" % s)
        return False
    cmd = "crmadmin -S %s" % dc
    cnt = 0
    output_started = 0
    while True:
        s = get_stdout(add_sudo(cmd))
        if not s.startswith("Status"):
            common_warn("%s unexpected output: %s" % (cmd,s))
            return False
        try: dc_status = s.split()[-2]
        except:
            common_warn("%s unexpected output: %s" % (cmd,s))
            return False
        if dc_status == "S_IDLE":
            if output_started:
                sys.stderr.write(" done\n")
            return True
        time.sleep(0.1)
        if show_progress:
            if not output_started:
                output_started = 1
                sys.stderr.write("waiting for %s to finish ." % what)
            cnt += 1
            if cnt % 5 == 0:
                sys.stderr.write(".")

def is_id_valid(id):
    """
    Verify that the id follows the definition:
    http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-qualnames
    """
    if not id:
        return False
    id_re = "^[A-Za-z_][\w._-]*$"
    return re.match(id_re,id)
def check_filename(fname):
    """
    Verify that the string is a filename.
    """
    fname_re = "^[^/]+$"
    return re.match(fname_re,id)

def is_process(s):
    proc = subprocess.Popen("ps -e -o pid,command | grep -qs '%s'" % s, \
        shell=True, stdout=subprocess.PIPE)
    proc.wait()
    return proc.returncode == 0
def cluster_stack():
    if is_process("heartbeat:.[m]aster"):
        return "heartbeat"
    elif is_process("[a]isexec"):
        return "openais"
    return ""

def edit_file(fname):
    'Edit a file.'
    if not fname:
        return
    if not user_prefs.editor:
        return
    return ext_cmd("%s %s" % (user_prefs.editor,fname))

def page_string(s):
    'Write string through a pager.'
    if not s:
        return
    w,h = get_winsize()
    if s.count('\n') < h:
        print s
    elif not user_prefs.pager or not sys.stdout.isatty() or options.batch:
        print s
    else:
        opts = ""
        if user_prefs.pager == "less":
            opts = "-R"
        pipe_string("%s %s" % (user_prefs.pager,opts), s)

def get_winsize():
    try:
        import curses
        curses.setupterm()
        w = curses.tigetnum('cols')
        h = curses.tigetnum('lines')
    except:
        try:
            w = os.environ['COLS']
            h = os.environ['LINES']
        except:
            w = 80; h = 25
    return w,h
def multicolumn(l):
    '''
    A ls-like representation of a list of strings.
    A naive approach.
    '''
    min_gap = 2
    w,h = get_winsize()
    max_len = 8
    for s in l:
        if len(s) > max_len:
            max_len = len(s)
    cols = w/(max_len + min_gap)  # approx.
    col_len = w/cols
    for i in range(len(l)/cols + 1):
        s = ''
        for j in range(i*cols,(i+1)*cols):
            if not j < len(l):
                break
            if not s:
                s = "%-*s" % (col_len,l[j])
            elif (j+1)%cols == 0:
                s = "%s%s" % (s,l[j])
            else:
                s = "%s%-*s" % (s,col_len,l[j])
        if s:
            print s

def find_value(pl,name):
    for n,v in pl:
        if n == name:
            return v
    return None

def lines2cli(s):
    '''
    Convert a string into a list of lines. Replace continuation
    characters. Strip white space, left and right. Drop empty lines.
    '''
    cl = []
    l = s.split('\n')
    cum = []
    for p in l:
        p = p.strip()
        if p.endswith('\\'):
            p = p.rstrip('\\')
            cum.append(p)
        else:
            cum.append(p)
            cl.append(''.join(cum).strip())
            cum = []
    if cum: # in case s ends with backslash
        cl.append(''.join(cum))
    return [x for x in cl if x]

user_prefs = UserPrefs.getInstance()
options = Options.getInstance()
vars = Vars.getInstance()
# vim:ts=4:sw=4:et: