def main(argv=None):
    ##############################################################################
    # Get a parser from omni that understands omni options
    ##############################################################################
    parser = omni.getParser()
    # update usage for help message
    omni_usage = parser.get_usage()
    parser.set_usage(
        omni_usage + "\naddMemberToSliceAndSlivers.py adds " +
        "the given member to the given slice and installs " +
        "their SSH keys on all slivers known to the CH plus at all specified aggregates.\n "
        + "Takes slice name and username as arguments")

    # options is an optparse.Values object, and args is a list
    options, args = omni.parse_args(sys.argv[1:], parser=parser)

    if len(args) < 2:
        print "Usage: addMemberToSliceAndSlivers.py <slicename> <username>"
        sys.exit(-1)

    sliceName = args[0]
    userName = args[1]
    omniargs = ['addslicemember', sliceName, userName]

    print "Calling Omni to add %s to slice %s\n" % (userName, sliceName)
    try:
        text, retItem = omni.call(omniargs, options)
        if not retItem:
            print "\nFailed to add member to slice: %s" % text
            sys.exit(-1)
    except OmniError, oe:
        print "\nOmni call failed: %s\n" % oe
        sys.exit(-1)
Esempio n. 2
0
def parseArguments(argv=None):
    global slicename, options, config

    if options is not None:
        # The caller, presumably a script, gave us an optparse.Values storage object.
        # Passing this object to parser.parse_args replaces the storage - it is pass
        # by reference. Callers may not expect that. In particular, multiple calls in
        # separate threads will conflict.
        # Make a deep copy
        options = copy.deepcopy(options)
        argv = []

    parser = getParser()
    (options, args) = omni.parse_args(argv, options, parser=parser)

    if len(args) > 0:
        slicename = args[0]
    else:
        sys.exit(
            "Must pass in slicename as argument of script.\nRun '%s -h' for more information."
            % os.path.basename(sys.argv[0]))

    # Check if a command was given
    if options.command == '':
        sys.exit(
            "Must use the -m parameter to pass the command to be executed.\nRun '%s -h' for more information."
            % os.path.basename(sys.argv[0]))
def main(argv=None):
  ##############################################################################
  # Get a parser from omni that understands omni options
  ##############################################################################
  parser = omni.getParser()
  # update usage for help message
  omni_usage = parser.get_usage()
  parser.set_usage(omni_usage+"\naddMemberToSliceAndSlivers.py adds " + 
                   "the given member to the given slice and installs " +
                   "their SSH keys on all slivers known to the CH plus at all specified aggregates.\n " +
                   "Takes slice name and username as arguments")

  # options is an optparse.Values object, and args is a list
  options, args = omni.parse_args(sys.argv[1:], parser=parser)

  if len(args) < 2:
    print "Usage: addMemberToSliceAndSlivers.py <slicename> <username>"
    sys.exit(-1)

  sliceName = args[0]
  userName = args[1]
  omniargs = ['addslicemember', sliceName, userName]

  print "Calling Omni to add %s to slice %s\n" % (userName, sliceName)
  try:
    text, retItem = omni.call(omniargs, options)
    if not retItem:
      print "\nFailed to add member to slice: %s" % text
      sys.exit(-1)
  except OmniError, oe:
    print "\nOmni call failed: %s\n" % oe
    sys.exit(-1)
Esempio n. 4
0
def main(argv=None):
  ##############################################################################
  # Get a parser from omni that understands omni options
  ##############################################################################
  parser = omni.getParser()
  # update usage for help message
  omni_usage = parser.get_usage()
  parser.set_usage(omni_usage+"\nrenewSliceAndSlivers.py renews the given slice and all slivers at aggregates known to the GENI CH for 60 days.\n " +
                   "Takes slice name as argument")

  # options is an optparse.Values object, and args is a list
  options, args = omni.parse_args(sys.argv[1:], parser=parser)

  sliceName = args[0]
  newDate = datetime.datetime.utcnow() + datetime.timedelta(days=60)
  # Strip fractional seconds from times to avoid errors at PG AMs
  newDate = newDate.replace(microsecond=0)
  retcode = 0

  for command in ['renewslice', 'renewsliver']:
    # Here we use --raise-error-on-v2-amapi-error. Note though that if 1 AM has a problem, the script stops. Is that what we want?
    # IE will all AMs return code 0 if they renew the slice alap?
    # Could supply arg '--warn' to turn down logging. But then we'd want this script to have Omni write to a log file.
    omniargs = ['--alap', '--useSliceAggregates', '--raise-error-on-v2-amapi-error', command, sliceName, "'%s'" % newDate.isoformat()]

    print "Calling Omni to renew slice %s%s until %sZ\n" % (sliceName, (" slivers" if command=="renewsliver" else ""), newDate.isoformat())
    try:
      text, retItem = omni.call(omniargs, options)
    except OmniError, oe:
      print "\n ***** Omni call failed: %s\n" % oe
      retcode = str(oe)
      continue
    print text
    print "\n"
def main(argv=None):
    ##############################################################################
    # Get a parser from omni that understands omni options
    ##############################################################################
    parser = omni.getParser()
    # set usage for help message
    parser.set_usage(
        "renewSliceAndSlivers.py [-r projectname] <slicename>\n"
        + "renewSliceAndSlivers.py renews the given slice and all slivers at aggregates known to the GENI CH for 60 days.\n"
        + "Uses standard Omni config file and standard omni commandline options. Run 'omni -h' for details."
    )

    if len(sys.argv[1:]) == 0 or (len(sys.argv[1:]) == 1 and str(sys.argv[1]).lower() in ("-h", "-?", "--help")):
        parser.print_usage()
        return 0

    # options is an optparse.Values object, and args is a list
    options, args = omni.parse_args(sys.argv[1:], parser=parser)

    if not args or len(args) < 1:
        parser.print_usage()
        return 1

    sliceName = args[0]
    newDate = datetime.datetime.utcnow() + datetime.timedelta(days=60)
    # Strip fractional seconds from times to avoid errors at PG AMs
    newDate = newDate.replace(microsecond=0)
    retcode = 0

    for command in ["renewslice", "renewsliver"]:
        # Here we use --raise-error-on-v2-amapi-error. Note though that if 1 AM has a problem, the script stops. Is that what we want?
        # IE will all AMs return code 0 if they renew the slice alap?
        # Could supply arg '--warn' to turn down logging. But then we'd want this script to have Omni write to a log file.
        omniargs = [
            "--alap",
            "--useSliceAggregates",
            "--raise-error-on-v2-amapi-error",
            command,
            sliceName,
            "'%s'" % newDate.isoformat(),
        ]

        print "Calling Omni to renew slice %s%s until %sZ\n" % (
            sliceName,
            (" slivers" if command == "renewsliver" else ""),
            newDate.isoformat(),
        )
        try:
            text, retItem = omni.call(omniargs, options)
        except OmniError, oe:
            print "\n ***** Omni call failed: %s\n" % oe
            retcode = str(oe)
            continue
        print text
        print "\n"
def main(argv=None):
    ##############################################################################
    # Get a parser from omni that understands omni options
    ##############################################################################
    parser = omni.getParser()
    parser.set_usage("%s [options] username" % sys.argv[0])
    options, args = omni.parse_args(sys.argv[1:], parser=parser)

    # pull username from the command line
    if len(args) > 0:
        username = args[0].strip()
    else:
        username = None


#    if not username:
#      sys.exit( "Must provide a username as the first argument of script" )

##############################################################################
# And now call omni, and omni sees your parsed options and arguments
# (1) Run equivalent of 'omni.py listmyslices username'
# (2) For each returned slicename run equivalent of:
#        'omni.py print_slice_expiration slicename'
##############################################################################
# (1) Run equivalent of 'omni.py listmyslices username'
    if username:
        text, sliceList = omni.call(['listmyslices', username], options)
    else:
        text, sliceList = omni.call(['listmyslices'], options)
        username = "******"

    #  print some summary info
    printStr = "=" * 80 + "\n"
    if len(sliceList) > 0:
        printStr += "User %s has %d slice(s):\n" % (username, len(sliceList))
    else:
        printStr += "User %s has NO slices\n" % (username)

    # (2) For each returned slicename run equivalent of:
    #        'omni.py print_slice_expiration slicename'

    for slicename in sliceList:
        omniargs = []
        omniargs.append('print_slice_expiration')
        omniargs.append(slicename)
        text, expiration = omni.call(omniargs, options)

        printStr += "%s\n" % (str(expiration))
    printStr += "=" * 80
    return printStr
def main(argv=None):
  ##############################################################################
  # Get a parser from omni that understands omni options
  ##############################################################################
  parser = omni.getParser()
  parser.set_usage("%s [options] username"%sys.argv[0])
  options, args = omni.parse_args(sys.argv[1:], parser=parser)

  # pull username from the command line
  if len(args) > 0:
    username = args[0].strip()
  else:
    username = None
#    if not username:
#      sys.exit( "Must provide a username as the first argument of script" )

  ##############################################################################
  # And now call omni, and omni sees your parsed options and arguments
  # (1) Run equivalent of 'omni.py listmyslices username'
  # (2) For each returned slicename run equivalent of: 
  #        'omni.py print_slice_expiration slicename'
  ##############################################################################
  # (1) Run equivalent of 'omni.py listmyslices username'
  if username:
    text, sliceList = omni.call( ['listmyslices', username], options )
  else:
    text, sliceList = omni.call( ['listmyslices'], options )
    username = "******"
  
  #  print some summary info
  printStr = "="*80+"\n"
  if len(sliceList)>0:
    printStr += "User %s has %d slice(s):\n"%(username, len(sliceList))
  else:
    printStr += "User %s has NO slices\n"%(username)

  # (2) For each returned slicename run equivalent of: 
  #        'omni.py print_slice_expiration slicename'
  
  for slicename in sliceList:
    omniargs = []
    omniargs.append('print_slice_expiration')
    omniargs.append(slicename)
    text, expiration = omni.call( omniargs, options )        

    printStr += "%s\n"%(str(expiration))
  printStr += "="*80            
  return printStr
Esempio n. 8
0
def parseArguments( argv=None, opts=None ) :
  global slicename, options, config

  if opts is not None:
        # The caller, presumably a script, gave us an optparse.Values storage object.
        # Passing this object to parser.parse_args replaces the storage - it is pass
        # by reference. Callers may not expect that. In particular, multiple calls in
        # separate threads will conflict.
        # Make a deep copy
        options = copy.deepcopy(opts)
        argv = []

  parser = getParser()
  (options, args) = omni.parse_args(argv, options, parser=parser)

  if len(args) > 0:
      slicename = args[0]
  elif slicename == None:
      sys.exit("Must pass in slicename as argument of script.\nRun '%s -h' for more information."%sys.argv[0])
Esempio n. 9
0
def parseArguments( argv=None, opts=None ) :
  global slicename, options, config

  if opts is not None:
        # The caller, presumably a script, gave us an optparse.Values storage object.
        # Passing this object to parser.parse_args replaces the storage - it is pass
        # by reference. Callers may not expect that. In particular, multiple calls in
        # separate threads will conflict.
        # Make a deep copy
        options = copy.deepcopy(opts)
        argv = []

  parser = getParser()
  (options, args) = omni.parse_args(argv, options, parser=parser)

  if len(args) > 0:
      slicename = args[0]
  elif slicename == None:
      sys.exit("Must pass in slicename as argument of script.\nRun '%s -h' for more information."%sys.argv[0])
Esempio n. 10
0
def main(argv=None):
    ##############################################################################
    # Get a parser from omni that understands omni options
    ##############################################################################
    parser = omni.getParser()
    # update usage for help message
    omni_usage = parser.get_usage()
    parser.set_usage(
        omni_usage +
        "\nrenewSliceAndSlivers.py renews the given slice and all slivers at aggregates known to the GENI CH for 60 days.\n "
        + "Takes slice name as argument")

    # options is an optparse.Values object, and args is a list
    options, args = omni.parse_args(sys.argv[1:], parser=parser)

    sliceName = args[0]
    newDate = datetime.datetime.utcnow() + datetime.timedelta(days=60)
    # Strip fractional seconds from times to avoid errors at PG AMs
    newDate = newDate.replace(microsecond=0)
    retcode = 0

    for command in ['renewslice', 'renewsliver']:
        # Here we use --raise-error-on-v2-amapi-error. Note though that if 1 AM has a problem, the script stops. Is that what we want?
        # IE will all AMs return code 0 if they renew the slice alap?
        # Could supply arg '--warn' to turn down logging. But then we'd want this script to have Omni write to a log file.
        omniargs = [
            '--alap', '--useSliceAggregates',
            '--raise-error-on-v2-amapi-error', command, sliceName,
            "'%s'" % newDate.isoformat()
        ]

        print "Calling Omni to renew slice %s%s until %sZ\n" % (
            sliceName, (" slivers" if command == "renewsliver" else ""),
            newDate.isoformat())
        try:
            text, retItem = omni.call(omniargs, options)
        except OmniError, oe:
            print "\n ***** Omni call failed: %s\n" % oe
            retcode = str(oe)
            continue
        print text
        print "\n"
Esempio n. 11
0
def parseArguments( argv=None ) :
  global  slicename, options, config

  if options is not None:
        # The caller, presumably a script, gave us an optparse.Values storage object.
        # Passing this object to parser.parse_args replaces the storage - it is pass
        # by reference. Callers may not expect that. In particular, multiple calls in
        # separate threads will conflict.
        # Make a deep copy
        options = copy.deepcopy(options)
        argv = []

  parser = getParser()
  (options, args) = omni.parse_args(argv, options, parser=parser)

  
  if len(args) > 0:
      slicename = args[0]
  else:
      sys.exit("Must pass in slicename as argument of script.\nRun '%s -h' for more information."%os.path.basename(sys.argv[0]))

  # Check if a command was given
  if options.command == '':
      sys.exit("Must use the -m parameter to pass the command to be executed.\nRun '%s -h' for more information."%os.path.basename(sys.argv[0]))
Esempio n. 12
0
            #print "Read config with pkgutils %s" % lcfile
        except Exception, e:
            #print "Failed to read .conf file using pkgutil: %s" % e
            # If we didn't get the file in the archive, use the .py version
            # I find this solution distasteful
            from gcf import stitcher_logging_deft
            try:
                with open(lcfile, 'w') as file:
                    file.write(stitcher_logging_deft.DEFT_STITCHER_LOGGING_CONFIG)
            except Exception, e2:
                sys.exit("Error configuring logging: Could not write (from python default) logging config file %s: %s" % (lcfile, e2))
            #print "Read from logging config from .py into tmp file %s" % lcfile
    parser.set_defaults(logconfig=lcfile)

    # Have omni use our parser to parse the args, manipulating options as needed
    options, args = omni.parse_args(argv, parser=parser)

    # If there is no fileDir, then we try to write to the CWD. In some installations, that will
    # fail. So test writing to CWD. If that fails, set fileDir to a temp dir to write files ther.
    if not options.fileDir:
        testfile = None
        handle = None
        try:
            import tempfile
            handle, testfile = tempfile.mkstemp(dir='.')
            #print "Can write to CWD: created %s" % testfile
            os.close(handle)
        except Exception, e:
            #print "Cannot write to CWD '%s' for output files: %s" % (os.path.abspath('.'), e)
            tmpdir = os.path.normpath(os.getenv("TMPDIR", os.getenv("TMP", "/tmp")))
            if tmpdir and tmpdir != "" and not os.path.exists(tmpdir):
Esempio n. 13
0
            # If we didn't get the file in the archive, use the .py version
            # I find this solution distasteful
            from gcf import stitcher_logging_deft
            try:
                with open(lcfile, 'w') as file:
                    file.write(
                        stitcher_logging_deft.DEFT_STITCHER_LOGGING_CONFIG)
            except Exception, e2:
                sys.exit(
                    "Error configuring logging: Could not write (from python default) logging config file %s: %s"
                    % (lcfile, e2))
            #print "Read from logging config from .py into tmp file %s" % lcfile
    parser.set_defaults(logconfig=lcfile)

    # Have omni use our parser to parse the args, manipulating options as needed
    options, args = omni.parse_args(argv, parser=parser)

    # If there is no fileDir, then we try to write to the CWD. In some installations, that will
    # fail. So test writing to CWD. If that fails, set fileDir to a temp dir to write files ther.
    if not options.fileDir:
        testfile = None
        handle = None
        try:
            import tempfile
            handle, testfile = tempfile.mkstemp(dir='.')
            #print "Can write to CWD: created %s" % testfile
            os.close(handle)
        except Exception, e:
            #print "Cannot write to CWD '%s' for output files: %s" % (os.path.abspath('.'), e)
            tmpdir = os.path.normpath(
                os.getenv("TMPDIR", os.getenv("TMP", "/tmp")))
Esempio n. 14
0
def main(argv=None):
  ##############################################################################
  # Get a parser from omni that understands omni options
  ##############################################################################
  parser = omni.getParser()
  # update usage for help message
  omni_usage = parser.get_usage()
  parser.set_usage(omni_usage+"\nmyscript.py supports additional commands.\n\n\tCommands and their arguments are:\n\t\t\t[add stuff here]")

  ##############################################################################
  # Add additional optparse.OptionParser style options for your
  # script as needed.
  # Be sure not to re-use options already in use by omni for
  # different meanings, otherwise you'll raise an OptionConflictError
  ##############################################################################
  parser.add_option("--myScriptPrivateOption",
                    help="A non-omni option added by %s"%sys.argv[0],
                    action="store_true", default=False)
  # options is an optparse.Values object, and args is a list
  options, args = omni.parse_args(sys.argv[1:], parser=parser)
  if options.myScriptPrivateOption:
    # do something special for your private script's options
    print "Got myScriptOption"



  ##############################################################################
  # Try to read 2nd argument as an RSpec filename. Pull the AM URL and
  # and maybe slice name from that file.
  # Then construct omni args appropriately: command, slicename, action or rspecfile or datetime
  ##############################################################################
  omniargs = []
  if args and len(args)>1:
    sliceurn = None
    # Try to read args[1] as an RSpec filename to read
    rspecfile = args[1]
    rspec = None
    if rspecfile:
      print "Looking for slice name and AM URL in RSpec file %s" % rspecfile
      try:
        rspec = readFile(rspecfile)
      except:
        print "Failed to read rspec from '%s'. Not an RSpec? Will try to get AM/slice from args." % rspecfile

    if rspec:
    # Now parse the comments, whch look like this:
#<!-- Resources at AM:
#	URN: unspecified_AM_URN
#	URL: https://localhost:8001
# -->
# Reserved resources for:\n\tSlice: %s
# at AM:\n\tURN: %s\n\tURL: %s

      if not ("Resources at AM" in rspec or "Reserved resources for" in rspec):
        sys.exit("Could not find slice name or AM URL in RSpec '%s'" % rspec)
      amurn = None
      amurl = None
      # Pull out the AM URN and URL
      match = re.search(r"at AM:\n\tURN: (\S+)\n\tURL: (\S+)\n", rspec)
      if match:
        amurn = match.group(1)
        amurl = match.group(2)
        print "  Found AM %s (%s)" % (amurn, amurl)
        omniargs.append("-a")
        omniargs.append(amurl)

      # Pull out the slice name or URN if any
      if "Reserved resources for" in rspec:
        match = re.search(r"Reserved resources for:\n\tSlice: (\S+)\n\t", rspec)
        if match:
          sliceurn = match.group(1)
          print "  Found slice %s" % sliceurn

    command = args[0]
    rest = []
    if len(args) > 2:
      rest = args[2:]

    # If the command requires a slice and we didn't get a readable rspec from the rspecfile,
    # Then treat that as the slice
    if not sliceurn and rspecfile and not rspec:
      sliceurn = rspecfile
      rspecfile = None

    # construct the args in order
    omniargs.append(command)
    if sliceurn:
      omniargs.append(sliceurn)
    if rspecfile and command.lower() in ('createsliver', 'allocate'):
      omniargs.append(rspecfile)
    for arg in rest:
      omniargs.append(arg)
  elif len(args) == 1:
    omniargs = args
  else:
    print "Got no command or rspecfile. Run '%s -h' for more information."%sys.argv[0]
    return

  ##############################################################################
  # And now call omni, and omni sees your parsed options and arguments
  ##############################################################################
  print "Call Omni with args %s:\n" % omniargs
  try:
    text, retItem = omni.call(omniargs, options)
  except OmniError, oe:
    sys.exit("\nOmni call failed: %s" % oe)