コード例 #1
0
ファイル: auto.py プロジェクト: pentikousis/C-BAS-framework
 def processExpirationEmails(self):
     now = _asUTC(datetime.datetime.utcnow())
     self._log.debug("Expiration check: %s" % (str(now)))
     day_alert = []
     week_alert = []
     try:
         slivers = GeniDB.getSliverList(False)
         for sliver in slivers:
             sobj = GeniDB.getSliverObj(sliver["sliver_urn"])
             (urn, action) = sobj.emailCheck(now)
             if action == 1:
                 day_alert.append(urn)
                 self._log.info(
                     "[%s] Sent email for expiry within 30 hours" % (urn))
             elif action == 2:
                 week_alert.append(urn)
                 self._log.info("[%s] Sent email for expiry within 7 days" %
                                (urn))
             else:
                 self._log.debug(
                     "[%s] Expiration check: No email required for sliver expiration (%s)"
                     % (urn, sobj.getExpiration()))
         return jsonify({
             "status": "success",
             "day_alerts": day_alert,
             "week_alerts": week_alert
         })
     except Exception, e:
         self._log.exception("Exception")
         return jsonify(None, code=2, msg=traceback.format_exc())
コード例 #2
0
ファイル: sfaapi.py プロジェクト: HalasNet/felix
    def pub_DeleteSliver(self, xrn, creds, options={}):
        """Delete a sliver
    Stop all the slice's resources and remove the reservation.
    Returns True or False indicating whether it did this successfully.
    """
        try:
            self.pm.check_permissions("DeleteSliver", locals())
        except Exception as e:
            return self.buildPropertyList(GENI_ERROR_CODE.CREDENTIAL_INVALID, output=e)
        self._log.info("Is HERE:")
        try:
            slivers = GeniDB.getSliverList()
            self._log.info("Is HERE:")
            sliver = get_slice_details_from_slivers(slivers, xrn)
            self._log.info("Deleteing Sliver")
            self._log.info(sliver["slice_urn"])
            data = GeniDB.getSliverData(sliver["sliver_urn"], True)
            foam.geni.lib.deleteSliver(sliver_urn=sliver["sliver_urn"])

            # foam.task.emailGAPIDeleteSliver(data)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=True)

        except UnknownSlice as e:
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.SEARCHFAILED, output=msg)
        except Exception as e:
            msg = "Exception: %s" % str(e)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
        finally:
            return propertyList
コード例 #3
0
ファイル: gapi2.py プロジェクト: HalasNet/felix
 def pub_SliverStatus (self, slice_urn, credentials, options):
   """Returns the status of the reservation for this slice at this aggregate"""
   try:
     if CredVerifier.checkValid(credentials, "sliverstatus", slice_urn):
       self.recordAction("sliverstatus", credentials, slice_urn)
       result = {}
       sliver_urn = GeniDB.getSliverURN(slice_urn)
       if not sliver_urn:
         raise Exception("Sliver for slice URN (%s) does not exist" % (slice_urn))
       sdata = GeniDB.getSliverData(sliver_urn, True)
       status = foam.geni.lib.getSliverStatus(sliver_urn)
       result["geni_urn"] = sliver_urn
       result["geni_status"] = status
       result["geni_resources"] = [{"geni_urn" : sliver_urn, "geni_status": status, "geni_error" : ""}]
       result["foam_status"] = sdata["status"]
       result["foam_expires"] = sdata["expiration"]
       result["foam_pend_reason"] = sdata["pend_reason"]
       propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=result)
   except UnknownSlice as e:
     msg = "Attempt to get status on unknown sliver for slice %s" % (slice_urn)
     propertyList = self.buildPropertyList(GENI_ERROR_CODE.SEARCHFAILED, output=msg)
     e.log(self._log, msg, logging.INFO)
   except Exception as e:
     msg = "Exception: %s" % str(e)
     propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
     self._log.exception(msg)
   finally:
     return propertyList
コード例 #4
0
    def priv_DeleteSliver(self, slice_urn, credentials, options=None):
        try:
            #if CredVerifier.checkValid(credentials, "deletesliver", slice_urn):
            if True:
                self.recordAction("deletesliver", credentials, slice_urn)
                if GeniDB.getSliverURN(slice_urn) is None:
                    raise Fault(
                        "DeleteSliver",
                        "Sliver for slice URN (%s) does not exist" %
                        (slice_urn))
                    return self.errorResult(12,
                                            "")  #not sure if this is needed
                sliver_urn = GeniDB.getSliverURN(slice_urn)
                data = GeniDB.getSliverData(sliver_urn, True)
                foam.geni.lib.deleteSliver(sliver_urn=sliver_urn)
                foam.task.emailGAPIDeleteSliver(data)
                return self.successResult(True)
            return self.successResult(False)

        except UnknownSlice, x:
            self._log.info(
                "Attempt to delete unknown sliver for slice URN %s" %
                (slice_urn))
            x._foam_logged = True
            raise x
コード例 #5
0
def renewSliver (slice_urn, creds, exptime):
  from foam.geni.db import GeniDB

  sliver_urn = GeniDB.getSliverURN(slice_urn)

  reqexp = dateutil.parser.parse(str(exptime))
  reqexp = _asUTC(reqexp)

  max_expiration = _asUTC(datetime.datetime.utcnow()) + ConfigDB.getConfigItemByKey("geni.max-lease").getValue()

  if reqexp > max_expiration:
    raise BadSliverExpiration(
      "The requested expiration date (%s) is past the allowed maximum expiration (%s)." %
        (reqexp, max_expiration))

  for cred in creds:
    credexp = _asUTC(cred.expiration)
    if reqexp > credexp:
      continue
    else:
      GeniDB.updateSliverExpiration(sliver_urn, reqexp)
      sobj = GeniDB.getSliverObj(sliver_urn)
      sobj.resetExpireEmail()
      sobj.store()
      return sliver_urn

  raise BadSliverExpiration(
      "No credential found whose expiration is greater than or equal to the requested sliver expiration (%s)" %
        (reqexp))
コード例 #6
0
ファイル: gapi2.py プロジェクト: HalasNet/felix
  def pub_DeleteSliver (self, slice_urn, credentials, options):
    """Delete a sliver

    Stop all the slice's resources and remove the reservation.
    Returns True or False indicating whether it did this successfully.

    """
    try:
      if CredVerifier.checkValid(credentials, "deletesliver", slice_urn):
        self.recordAction("deletesliver", credentials, slice_urn)
        if GeniDB.getSliverURN(slice_urn) is None:
          raise UnkownSlice(slice_urn)

        sliver_urn = GeniDB.getSliverURN(slice_urn)
        data = GeniDB.getSliverData(sliver_urn, True)

        foam.geni.lib.deleteSliver(sliver_urn = sliver_urn)

        foam.task.emailGAPIDeleteSliver(data)

        propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=True)

    except UnknownSlice as e:
      msg = "Attempt to delete unknown sliver for slice URN %s" % (slice_urn)
      propertyList = self.buildPropertyList(GENI_ERROR_CODE.SEARCHFAILED, output=msg)
      e.log(self._log, msg, logging.INFO)
    except Exception as e:
      msg = "Exception: %s" % str(e)
      propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
      self._log.exception("Exception")
    finally:
      return propertyList
コード例 #7
0
  def pub_CreateSliver (self, slice_urn, credentials, rspec, users):
    user_info = {}
    try:
      if CredVerifier.checkValid(credentials, "createsliver"):
        self.recordAction("createsliver", credentials, slice_urn)
        try:
          cert = Certificate(request.environ['CLIENT_RAW_CERT'])
          user_info["urn"] = cert.getURN()
          user_info["email"] = cert.getEmailAddress()
          self._log.debug("Parsed user cert with URN (%(urn)s) and email (%(email)s)" % user_info)
        except Exception, e:
          self._log.exception("UNFILTERED EXCEPTION")
          user_info["urn"] = None
          user_info["email"] = None
        sliver = foam.geni.lib.createSliver(slice_urn, credentials, rspec, user_info)

        approve = foam.geni.approval.analyzeForApproval(sliver)
        style = ConfigDB.getConfigItemByKey("geni.approval.approve-on-creation").getValue()
        if style == foam.geni.approval.NEVER:
          approve = False
        elif style == foam.geni.approval.ALWAYS:
          approve = True
        if approve:
          pid = foam.task.approveSliver(sliver.getURN(), AUTO_SLIVER_PRIORITY)
          self._log.debug("task.py launched for approve-sliver (PID: %d)" % pid)

        data = GeniDB.getSliverData(sliver.getURN(), True)
        foam.task.emailCreateSliver(data)

        return GeniDB.getManifest(sliver.getURN())
      return
コード例 #8
0
def importSliver(opts):
    # Quick dirty way to find out if a sliver exists
    try:
        GeniDB.getSliverPriority(opts["sliver_urn"])
        return
    except UnknownSliver, e:
        pass
コード例 #9
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
  def showSliver (self):
#    from foam.core.tracer import Tracer
#    Tracer.enable()

    if not request.json:
      return

    try:
      return_obj = {}

      self.validate(request.json, [("sliver_urn", (unicode,str))])

      sobj = GeniDB.getSliverObj(request.json["sliver_urn"])
      return_obj["sliver"] = sobj

      if request.json.has_key("flowspace") and request.json["flowspace"]:
        return_obj["flowspace"] = sobj.generateFlowEntries()

      if request.json.has_key("flowspec") and request.json["flowspec"]:
        return_obj["flowspec"] = sobj.json_flowspec()

      if request.json.has_key("rspec") and request.json["rspec"]:
        return_obj["rspec"] = GeniDB.getRspec(request.json["sliver_urn"])

#      path = Tracer.disable()
#      self._log.debug("Tracer path: %s" % (path))

      return jsonify(return_obj)
    except JSONValidationError, e:
      jd = e.__json__()
      return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #10
0
ファイル: lib.py プロジェクト: HalasNet/felix
def importSliver (opts):
  # Quick dirty way to find out if a sliver exists
  try:
    GeniDB.getSliverPriority(opts["sliver_urn"])
    return
  except UnknownSliver, e:
    pass
コード例 #11
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def gapi_CreateSliver(self, slice_urn, credentials, rspec, users, force_approval=False, options=None):	
   #GENI API imports
   from foam.geni.db import GeniDB, UnknownSlice, UnknownNode
   import foam.geni.approval
   import foam.geni.ofeliaapproval
   import sfa
   user_info = users
   try:
     if True:
       #self.recordAction("createsliver", credentials, slice_urn)
       try:
         self._log.debug("Parsed user cert with URN (%(urn)s) and email (%(email)s)" % users)
       except Exception, e:
         self._log.exception("UNFILTERED EXCEPTION")
         user_info["urn"] = None
         user_info["email"] = None
       sliver = foam.geni.lib.createSliver(slice_urn, credentials, rspec, user_info)
       style = ConfigDB.getConfigItemByKey("geni.approval.approve-on-creation").getValue()
       if style == foam.geni.approval.NEVER:
         approve = False
       elif style == foam.geni.approval.ALWAYS:
         approve = True
       else:
         approve = foam.geni.ofeliaapproval.of_analyzeForApproval(sliver)
       if approve or force_approval:
         pid = foam.task.approveSliver(sliver.getURN(), AUTO_SLIVER_PRIORITY)
         self._log.debug("task.py launched for approve-sliver (PID: %d)" % pid)	
       data = GeniDB.getSliverData(sliver.getURN(), True)
       foam.task.emailCreateSliver(data)
       return self.successResult(GeniDB.getManifest(sliver.getURN()))
     return		
コード例 #12
0
ファイル: lib.py プロジェクト: HalasNet/felix
def getAdvertisement ():
  NSMAP = {None: "%s" % (PGNS),
          "xs" : "%s" % (XSNS),
          "openflow" : "%s" % (OFNSv3)}

  rspec = ET.Element("rspec", nsmap = NSMAP)
  rspec.attrib["{%s}schemaLocation" % (XSNS)] = PGNS + " " \
              "http://www.geni.net/resources/rspec/3/ad.xsd " + \
              OFNSv3 + " " \
              "http://www.geni.net/resources/rspec/ext/openflow/3/of-ad.xsd"
  rspec.attrib["type"] = "advertisement"

  links = FV.getLinkList()
  devices = FV.getDeviceList()
  fvversion = FV.getFVVersion()
  db_devices = GeniDB.getDeviceSet()
  GeniDB.refreshDevices(devices)

  for dpid in devices:
    db_devices.discard(dpid)
    addAdDevice(rspec, dpid)

  for dpid in db_devices:
    addAdDevice(rspec, dpid, False)
 
#getLinks START    
  for link in links:
    addAdLink(rspec, link)
#getLinks END 
    
  xml = StringIO()
  ET.ElementTree(rspec).write(xml)
  return xml.getvalue()
コード例 #13
0
ファイル: legacyexpedientapi.py プロジェクト: HalasNet/felix
 def priv_CreateSliver(self, slice_urn, credentials, rspec, users, force_approval=False, options=None):	
   #user_info = {}
   user_info = users
   try:
     #if CredVerifier.checkValid(credentials, "createsliver"):
     if True:
       self.recordAction("createsliver", credentials, slice_urn)
       try:
         #cert = Certificate(request.environ['CLIENT_RAW_CERT'])
         #user_info["urn"] = cert.getURN()
         #user_info["email"] = cert.getEmailAddress()
         self._log.debug("Parsed user cert with URN (%(urn)s) and email (%(email)s)" % users)
       except Exception, e:
         self._log.exception("UNFILTERED EXCEPTION")
         user_info["urn"] = None
         user_info["email"] = None
       from foam.app import admin_apih
       if not admin_apih.vlan_automation_on:
         sliver = foam.geni.lib.createSliver(slice_urn, credentials, rspec, user_info)
         style = ConfigDB.getConfigItemByKey("geni.approval.approve-on-creation").getValue()
         if style == foam.geni.approval.NEVER:
           approve = False
         elif style == foam.geni.approval.ALWAYS:
           approve = True
         else:
           approve = foam.geni.ofeliaapproval.of_analyzeForApproval(sliver)
         if approve or force_approval:
           pid = foam.task.approveSliver(sliver.getURN(), AUTO_SLIVER_PRIORITY)
           self._log.debug("task.py launched for approve-sliver (PID: %d)" % pid)	
       else:
         free_vlan_list = self.pub_get_offered_vlans(1)
         free_vlan = free_vlan_list[0]
         slice_id = slice_urn.split("+slice+")[1].split(":")[0].split("id_")[1].split("name_")[0]
         #filedir = './opt/ofelia/ofam/local/db'
         #filename = os.path.join(filedir, 'expedient_slices_info.json')
         #f = open(filename, 'r')
         #self.slice_info_dict = json.load(f)
         #f.close()
         if (slice_id == "") or (slice_id not in self.slice_info_dict): 
           self._log.exception("The slice id you specified is non-existent")
           raise Exception
         updated_slice_info_dict = self.slice_info_dict.copy()
         for sliv_pos, sliver in enumerate(self.slice_info_dict[slice_id]['switch_slivers']):
           for sfs_pos, sfs in enumerate(sliver['flowspace']):   
             updated_slice_info_dict[slice_id]['switch_slivers'][sliv_pos]['flowspace'][sfs_pos]['vlan_id_start'] = free_vlan
             updated_slice_info_dict[slice_id]['switch_slivers'][sliv_pos]['flowspace'][sfs_pos]['vlan_id_end'] = free_vlan
         all_efs = self.create_slice_fs(updated_slice_info_dict[slice_id]['switch_slivers'])
         new_slice_of_rspec = create_ofv3_rspec(slice_id, updated_slice_info_dict[slice_id]['project_name'], updated_slice_info_dict[slice_id]['project_desc'], \
                                     updated_slice_info_dict[slice_id]['slice_name'], updated_slice_info_dict[slice_id]['slice_desc'], \
                                     updated_slice_info_dict[slice_id]['controller_url'], updated_slice_info_dict[slice_id]['owner_email'], \
                                     updated_slice_info_dict[slice_id]['owner_password'], \
                                     updated_slice_info_dict[slice_id]['switch_slivers'], all_efs)
         self.slice_info_dict = updated_slice_info_dict.copy()
         sliver = foam.geni.lib.createSliver(slice_urn, credentials, new_slice_of_rspec, user_info)
         pid = foam.task.approveSliver(sliver.getURN(), AUTO_SLIVER_PRIORITY)
         self._log.debug("task.py launched for approve-sliver (PID: %d)" % pid)
       data = GeniDB.getSliverData(sliver.getURN(), True)
       foam.task.emailCreateSliver(data)
       return self.successResult(GeniDB.getManifest(sliver.getURN()))
     return
コード例 #14
0
    def pub_DeleteSliver(self, xrn, creds, options={}):
        """Delete a sliver
    Stop all the slice's resources and remove the reservation.
    Returns True or False indicating whether it did this successfully.
    """
        try:
            self.pm.check_permissions('DeleteSliver', locals())
        except Exception as e:
            return self.buildPropertyList(GENI_ERROR_CODE.CREDENTIAL_INVALID,
                                          output=e)
        self._log.info("Is HERE:")
        try:
            slivers = GeniDB.getSliverList()
            self._log.info("Is HERE:")
            sliver = get_slice_details_from_slivers(slivers, xrn)
            self._log.info("Deleteing Sliver")
            self._log.info(sliver["slice_urn"])
            data = GeniDB.getSliverData(sliver["sliver_urn"], True)
            foam.geni.lib.deleteSliver(sliver_urn=sliver["sliver_urn"])

            #foam.task.emailGAPIDeleteSliver(data)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS,
                                                  value=True)

        except UnknownSlice as e:
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.SEARCHFAILED,
                                                  output=msg)
        except Exception as e:
            msg = "Exception: %s" % str(e)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR,
                                                  output=msg)
        finally:
            return propertyList
コード例 #15
0
  def pub_ListResources (self, credentials, options):
    try:
      CredVerifier.checkValid(credentials, [])

      compressed = options.get("geni_compressed", False)
      urn = options.get("geni_slice_urn", None)

      if urn:
        CredVerifier.checkValid(credentials, "getsliceresources", urn)
        self.recordAction("listresources", credentials, urn)
        sliver_urn = GeniDB.getSliverURN(urn)
        if sliver_urn is None:
          raise Fault("ListResources", "Sliver for slice URN (%s) does not exist" % (urn))
        rspec = GeniDB.getManifest(sliver_urn)
      else:
        self.recordAction("listresources", credentials)
        rspec = foam.geni.lib.getAdvertisement()
      if compressed:
        zrspec = zlib.compress(rspec)
        rspec = base64.b64encode(zrspec)

      return rspec
    except ExpatError, e:
      self._log.error("Error parsing credential strings")
      e._foam_logged = True
      raise e
コード例 #16
0
 def pub_change_slice_controller(self, slice_id, controller_url, **kwargs):
     slice_id = slice_id.replace(":", "_")
     slice_id = slice_id.replace("name_", "nam__")
     '''
 Changes the slice controller url.
 '''
     if slice_id not in self.slice_info_dict:
         self._log.info(
             "Slice is probably not started yet, doing nothing...")
         return ""
         #raise Exception("Something went wrong with the fs recovery")
     #retrieve updated dict as a json file from foam db folder
     filedir = './opt/ofelia/ofam/local/db'
     filename = os.path.join(filedir, 'expedient_slices_info.json')
     if os.path.isfile(filename):
         f = open(filename, 'r')
         self.slice_info_dict = json.load(f)
         f.close()
     else:
         self._log.info(
             "Slice is probably not started yet, doing nothing...")
         return ""
     slice_of_rspec = create_ofv3_rspec(
         slice_id, self.slice_info_dict[slice_id]['project_name'],
         self.slice_info_dict[slice_id]['project_desc'],
         self.slice_info_dict[slice_id]['slice_name'],
         self.slice_info_dict[slice_id]['slice_desc'], controller_url,
         self.slice_info_dict[slice_id]['owner_email'],
         self.slice_info_dict[slice_id]['owner_password'],
         self.slice_info_dict[slice_id]['switch_slivers'],
         self.create_slice_fs(
             self.slice_info_dict[slice_id]['switch_slivers']))
     self.slice_info_dict[slice_id]['controller_url'] = controller_url
     slice_urn = "urn:publicid:IDN+openflow:foam:" + str(
         THIS_SITE_TAG) + "+slice+" + "id_" + str(slice_id) + "name_" + str(
             self.slice_info_dict[slice_id]['slice_name'])
     creds = []  #creds are not needed at least for now: to be fixed
     user_info = {}
     user_info["urn"] = "urn:publicid:IDN+openflow:foam" + str(
         THIS_SITE_TAG) + "+ch+" + "user+" + str(
             self.slice_info_dict[slice_id]['owner_email'])  #temp hack
     user_info["email"] = str(self.slice_info_dict[slice_id]['owner_email'])
     if GeniDB.sliceExists(slice_urn):
         sliv_urn = GeniDB.getSliverURN(slice_urn)
     else:
         raise Exception(
             "Something went wrong with the fs recovery, slice does not exist!"
         )
     sliver = GeniDB.getSliverObj(sliv_urn)
     is_allocated_by_FV = GeniDB.getEnabled(sliv_urn)
     was_allocated_by_FV = is_allocated_by_FV
     try:
         #old_exp_shutdown_success = legexpgapi2_apih.pub_Shutdown(slice_urn, creds, [])
         old_exp_shutdown_success = self.priv_DeleteSliver(
             slice_urn, creds, [])
     except Exception, e:
         import traceback
         traceback.print_exc()
         raise Exception("Exception while trying to shutdown old slice!")
コード例 #17
0
ファイル: lib.py プロジェクト: HalasNet/felix
def deleteSliver (slice_urn = None, sliver_urn = None):
  slice_name = GeniDB.getFlowvisorSliceName(slice_urn=slice_urn, sliver_urn = sliver_urn)
  if FV.sliceExists(slice_name):
#    stats = FV.getCombinedStats(slice_name)
#    GeniDB.insertFinalStats(slice_urn, stats)
    FV.deleteSlice(slice_name)
  GeniDB.deleteSliver(slice_urn=slice_urn, sliver_urn=sliver_urn)
  foam.geni.approval.rebuildDB()
コード例 #18
0
ファイル: sfaapi.py プロジェクト: HalasNet/felix
    def pub_CreateSliver(self, slice_xrn, creds, rspec, users, options):
        """Allocate resources to a slice

    Reserve the resources described in the given RSpec for the given slice, returning a manifest RSpec of what has been reserved.

    """
        try:
            self.pm.check_permissions("CreateSliver", locals())
        except Exception as e:
            return self.buildPropertyList(GENI_ERROR_CODE.CREDENTIAL_INVALID, output=e)
        self.recordAction("createsliver", creds, slice_xrn)
        user_info = {}
        user_info["urn"] = None
        user_info["email"] = None
        request.environ.pop("CLIENT_RAW_CERT", None)
        sliver = foam.geni.lib.createSliver(slice_xrn, creds, rspec, user_info)
        try:
            approve = foam.geni.approval.analyzeForApproval(sliver)
            style = ConfigDB.getConfigItemByKey("geni.approval.approve-on-creation").getValue()
            if style == foam.geni.approval.NEVER:
                approve = False
            elif style == foam.geni.approval.ALWAYS:
                approve = True
            if approve:
                pid = foam.task.approveSliver(sliver.getURN(), self._auto_priority)

            data = GeniDB.getSliverData(sliver.getURN(), True)
            # foam.task.emailCreateSliver(data)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=GeniDB.getManifest(sliver.getURN()))

        except foam.geni.lib.RspecParseError as e:
            msg = str(e)
            self._log.info(e)
            return msg
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.BADARGS, output=msg)
        except foam.geni.lib.RspecValidationError as e:
            self._log.info(e)
            msg = str(e)
            return msg
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.BADARGS, output=msg)
        except foam.geni.lib.DuplicateSliver as ds:
            msg = "Attempt to create multiple slivers for slice [%s]" % (ds.slice_urn)
            self._log.info(msg)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
        except foam.geni.lib.UnknownComponentManagerID as ucm:
            msg = "Component Manager ID specified in %s does not match this aggregate." % (ucm.cid)
            self._log.info(msg)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
        except (foam.geni.lib.UnmanagedComponent, UnknownNode) as uc:
            msg = "DPID in component %s is unknown to this aggregate." % (uc.cid)
            self._log.info(msg)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
        except Exception as e:
            msg = "Exception %s" % str(e)
            self._log.info(e)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
        finally:
            return propertyList
コード例 #19
0
def deleteSliver(slice_urn=None, sliver_urn=None):
    slice_name = GeniDB.getFlowvisorSliceName(slice_urn=slice_urn,
                                              sliver_urn=sliver_urn)
    if FV.sliceExists(slice_name):
        #    stats = FV.getCombinedStats(slice_name)
        #    GeniDB.insertFinalStats(slice_urn, stats)
        FV.deleteSlice(slice_name)
    GeniDB.deleteSliver(slice_urn=slice_urn, sliver_urn=sliver_urn)
    foam.geni.approval.rebuildDB()
コード例 #20
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def setLocation (self):
   if not request.json:
     return
   try:
     self.validate(request.json, [("lat", float), ("long", float), ("dpid", (unicode,str)), ("country", (unicode,str))])
     GeniDB.setLocation(request.json["dpid"], request.json["country"], request.json["lat"], request.json["long"])
     return jsonify({"status" : "success"})
   except JSONValidationError, e:
     jd = e.__json__()
     return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #21
0
 def pub_Shutdown(self, slice_urn, credentials, options):
     """Perform an emergency shutdown of the resources in a slice at this aggregate"""
     if CredVerifier.checkValid(credentials, "shutdown", slice_urn):
         self.recordAction("shutdown", credentials, slice_urn)
         #foam.lib.shutdown(slice_urn)
         sliver_urn = GeniDB.getSliverURN(slice_urn)
         data = GeniDB.getSliverData(sliver_urn, True)
         foam.geni.lib.deleteSliver(sliver_urn=sliver_urn)
         return self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=True)
     return self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=False)
コード例 #22
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def adminSetSliverExpiration (self):
   if not request.json:
     return
   try:
     objs = self.validate(request.json, [("datetime", types.DateTime), ("urn", types.SliverURN)])
     GeniDB.updateSliverExpiration(objs["urn"], objs["datetime"])
     return jsonify({"status" : "success"})
   except JSONValidationError, e:
     jd = e.__json__()
     return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #23
0
ファイル: gapi2.py プロジェクト: HalasNet/felix
 def pub_Shutdown (self, slice_urn, credentials, options):
   """Perform an emergency shutdown of the resources in a slice at this aggregate"""
   if CredVerifier.checkValid(credentials, "shutdown", slice_urn):
     self.recordAction("shutdown", credentials, slice_urn)
     #foam.lib.shutdown(slice_urn)
     sliver_urn = GeniDB.getSliverURN(slice_urn)
     data = GeniDB.getSliverData(sliver_urn, True)
     foam.geni.lib.deleteSliver(sliver_urn = sliver_urn)
     return self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=True)
   return self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=False)
コード例 #24
0
ファイル: lib.py プロジェクト: HalasNet/felix
def approveSliver (request, logger):
  try:
    jsonValidate(request.json, [("sliver_urn", (unicode,str)), ("priority", int)], logger)

    if (not request.json.has_key("sliver_urn")) or (not request.json.has_key("priority")):
      return jsonify({"exception" : "You must specify a sliver_urn and priority"})
    slice_name = GeniDB.getFlowvisorSliceName(sliver_urn=request.json["sliver_urn"])
    if FV.sliceExists(slice_name):
      return jsonify({"Fault" : "Flowvisor slice '%s' already exists" % (slice_name)})

    sobj = GeniDB.getSliverObj(request.json["sliver_urn"])
    GeniDB.setSliverStatus(request.json["sliver_urn"], True)
    GeniDB.setSliverPriority(request.json["sliver_urn"], request.json["priority"])

    GeniDB.commit()

    foam.geni.approval.AppData.addSliver(sobj)

    sobj.createSlice()
    sobj.insertFlowspace(request.json["priority"])
    sobj.insertVirtualLink()

    data = GeniDB.getSliverData(sobj.getURN(), True)
    foam.task.emailApproveSliver(data)

    return jsonify(None)
  except JSONValidationError, e:
    jd = e.__json__()
    return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #25
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
  def removeDatapath (self):
    if not request.json:
      return

    try:
      self.validate(request.json, [("dpid", (unicode,str))])
      GeniDB.removeDatapath(request.json["dpid"])
      return jsonify({"status" : "success"})
    except JSONValidationError, e:
      jd = e.__json__()
      return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #26
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def setTrigger (self):
   if not request.json:
     return
   try:
     obj = self.validate(request.json, [("type", types.TriggerType), ("start", (str,unicode)),
                             ("end", (str,unicode)), ("event", types.EventType),
                             ("action", None)])
     GeniDB.addTrigger(obj["type"], obj["start"], obj["end"], obj["event"], obj["action"])
   except JSONValidationError, e:
     jd = e.__json__()
     return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #27
0
ファイル: legacyexpedientapi.py プロジェクト: HalasNet/felix
 def pub_change_slice_controller(self, slice_id, controller_url, **kwargs):
   slice_id   = slice_id.replace(":","_")
   slice_id   = slice_id.replace("name_","nam__")
   '''
   Changes the slice controller url.
   '''
   if slice_id not in self.slice_info_dict:
     self._log.info("Slice is probably not started yet, doing nothing...")
     return ""
     #raise Exception("Something went wrong with the fs recovery")
   #retrieve updated dict as a json file from foam db folder
   filedir = './opt/ofelia/ofam/local/db'
   filename = os.path.join(filedir, 'expedient_slices_info.json')
   if os.path.isfile(filename):
     f = open(filename, 'r')
     self.slice_info_dict = json.load(f)
     f.close()
   else:
     self._log.info("Slice is probably not started yet, doing nothing...")
     return ""
   slice_of_rspec = create_ofv3_rspec(slice_id, self.slice_info_dict[slice_id]['project_name'], 
                                      self.slice_info_dict[slice_id]['project_desc'],
                                      self.slice_info_dict[slice_id]['slice_name'],
                                      self.slice_info_dict[slice_id]['slice_desc'], controller_url,
                                      self.slice_info_dict[slice_id]['owner_email'],
                                      self.slice_info_dict[slice_id]['owner_password'],
                                      self.slice_info_dict[slice_id]['switch_slivers'],
                                      self.create_slice_fs(self.slice_info_dict[slice_id]['switch_slivers']))
   self.slice_info_dict[slice_id]['controller_url'] = controller_url
   slice_urn = "urn:publicid:IDN+openflow:foam:"+ str(THIS_SITE_TAG) +"+slice+" + "id_" + str(slice_id) + "name_" + str(self.slice_info_dict[slice_id]['slice_name'])
   creds = [] #creds are not needed at least for now: to be fixed
   user_info = {}
   user_info["urn"] = "urn:publicid:IDN+openflow:foam"+ str(THIS_SITE_TAG) +"+ch+" + "user+" + str(self.slice_info_dict[slice_id]['owner_email']) #temp hack
   user_info["email"] = str(self.slice_info_dict[slice_id]['owner_email'])
   if GeniDB.sliceExists(slice_urn):
     sliv_urn = GeniDB.getSliverURN(slice_urn)
   else:
     raise Exception("Something went wrong with the fs recovery, slice does not exist!")
   sliver = GeniDB.getSliverObj(sliv_urn) 
   is_allocated_by_FV = GeniDB.getEnabled(sliv_urn)
   was_allocated_by_FV = is_allocated_by_FV
   try:
     #old_exp_shutdown_success = legexpgapi2_apih.pub_Shutdown(slice_urn, creds, [])
     old_exp_shutdown_success = self.priv_DeleteSliver(slice_urn, creds, [])
   except Exception, e:
     import traceback
     traceback.print_exc()
     raise Exception("Exception while trying to shutdown old slice!")
コード例 #28
0
    def pub_RenewSliver(self, slice_urn, credentials, exptime, options):
        """Renew the reservation for resources in this slice"""
        try:
            if CredVerifier.checkValid(credentials, "renewsliver", slice_urn):
                self.recordAction("renewsliver", credentials, slice_urn)
                creds = CredVerifier.fromStrings(credentials, "renewsliver",
                                                 slice_urn)
                sliver_urn = foam.lib.renewSliver(slice_urn, creds, exptime)

                data = GeniDB.getSliverData(sliver_urn, True)
                foam.task.emailRenewSliver(data)

                propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS,
                                                      value=True)
        except foam.lib.BadSliverExpiration as e:
            msg = "Bad expiration request: %s" % (e.msg)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR,
                                                  output=msg)
            e.log(self._log, msg, logging.INFO)
        except Exception:
            msg = "Exception"
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR,
                                                  output=msg)
            self._log.exception("Exception")
        finally:
            return propertyList
コード例 #29
0
ファイル: sfaapi.py プロジェクト: HalasNet/felix
 def pub_SliverStatus(self, slice_xrn=None, creds=[], options={}):
     try:
         self.pm.check_permissions("SliverStatus", locals())
     except Exception as e:
         return self.buildPropertyList(GENI_ERROR_CODE.CREDENTIAL_INVALID, output=e)
     try:
         slivers = GeniDB.getSliverList()
         try:
             sliver = get_slice_details_from_slivers(slivers, slice_xrn)
         except:
             raise Exception("Sliver for slice URN (%s) does not exist" % (slice_xrn))
         result = dict()
         result["slice_urn"] = slice_xrn
         result["sliver_urn"] = sliver["sliver_urn"]
         result["status"] = sliver["status"]
         result["created"] = sliver["creation"]
         result["description"] = sliver["desc"]
         result["expires"] = sliver["expiration"]
         propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS, value=result)
     except UnknownSlice as e:
         msg = "Attempt to get status on unknown sliver for slice %s" % (slice_xrn)
         propertyList = self.buildPropertyList(GENI_ERROR_CODE.SEARCHFAILED, output=msg)
         e.log(self._log, msg, logging.INFO)
     except Exception as e:
         msg = "Exception: %s" % str(e)
         propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR, output=msg)
         self._log.exception(msg)
     finally:
         return propertyList
コード例 #30
0
 def pub_SliverStatus(self, slice_xrn=None, creds=[], options={}):
     try:
         self.pm.check_permissions('SliverStatus', locals())
     except Exception as e:
         return self.buildPropertyList(GENI_ERROR_CODE.CREDENTIAL_INVALID,
                                       output=e)
     try:
         slivers = GeniDB.getSliverList()
         try:
             sliver = get_slice_details_from_slivers(slivers, slice_xrn)
         except:
             raise Exception("Sliver for slice URN (%s) does not exist" %
                             (slice_xrn))
         result = dict()
         result["slice_urn"] = slice_xrn
         result["sliver_urn"] = sliver["sliver_urn"]
         result["status"] = sliver["status"]
         result["created"] = sliver["creation"]
         result["description"] = sliver["desc"]
         result["expires"] = sliver["expiration"]
         propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS,
                                               value=result)
     except UnknownSlice as e:
         msg = "Attempt to get status on unknown sliver for slice %s" % (
             slice_xrn)
         propertyList = self.buildPropertyList(GENI_ERROR_CODE.SEARCHFAILED,
                                               output=msg)
         e.log(self._log, msg, logging.INFO)
     except Exception as e:
         msg = "Exception: %s" % str(e)
         propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR,
                                               output=msg)
         self._log.exception(msg)
     finally:
         return propertyList
コード例 #31
0
    def pub_RenewSliver(self,
                        slice_xrn=None,
                        creds=[],
                        expiration_time=None,
                        options={}):
        try:
            self.pm.check_permissions('Start', locals())
        except Exception as e:
            return self.buildPropertyList(GENI_ERROR_CODE.CREDENTIAL_INVALID,
                                          output=e)
        try:
            sliver_urn = foam.lib.renewSliver(slice_xrn, creds,
                                              expiration_time)
            data = GeniDB.getSliverData(sliver_xrn, True)
            #foam.task.emailRenewSliver(data)

            propertyList = self.buildPropertyList(GENI_ERROR_CODE.SUCCESS,
                                                  value=True)
        except foam.lib.BadSliverExpiration as e:
            msg = "Bad expiration request: %s" % (e.msg)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR,
                                                  output=msg)
            e.log(self._log, msg, logging.INFO)
        except Exception as e:
            msg = "Exception: %s" % str(e)
            propertyList = self.buildPropertyList(GENI_ERROR_CODE.ERROR,
                                                  output=msg)
            self._log.exception(msg)
        finally:
            return propertyList
コード例 #32
0
ファイル: lib.py プロジェクト: HalasNet/felix
def addAdDevice (rspec, dpid, active=True):
  switch_urn = generateSwitchComponentID(dpid)

  od = ET.SubElement(rspec, "{%s}datapath" % (OFNSv3))
  od.attrib["component_id"] = switch_urn
  od.attrib["component_manager_id"] = getManagerID()
  od.attrib["dpid"] = dpid

  locdata = GeniDB.getLocationData(dpid, switch_urn)
  if locdata:
    ET.SubElement(od, "{%s}location" % (OFNSv3), country=locdata.country, latitude=locdata.lat, longitude=locdata.long)

  attachments = TopoDB.getDPIDAttachments(dpid)

  if active:
    ports = FV.getDevicePorts(dpid)
    for port in ports:
      if (port.features == None):
        p = ET.SubElement(od, "{%s}port" % (OFNSv3), num=str(port.num), name=port.name)
      else:
        p = ET.SubElement(od, "{%s}port" % (OFNSv3), num=str(port.num), name=port.name, features=port.features)
      for info in attachments.setdefault(port.name, []):
        a = ET.SubElement(p, "{%s}attachment" % (OFNSv3))
        a.attrib["remote_component_id"] = info.remote_component_id
        a.attrib["remote_port"] = info.remote_port
        a.attrib["desc"] = info.desc
コード例 #33
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def getSliverFlowspace (self):
   if not request.json:
     return
   try:
     self.validate(request.json, [("sliver_urn", (unicode,str))])
     sobj = GeniDB.getSliverObj(request.json["sliver_urn"])
     return jsonify({"flowspace" : sobj.generateFlowEntries()})
   except JSONValidationError, e:
     return jsonify(e.__json__())
コード例 #34
0
ファイル: lib.py プロジェクト: HalasNet/felix
def getSliverStatus (sliver_urn):
  try:
    slice_name = GeniDB.getFlowvisorSliceName(sliver_urn=sliver_urn)
    if FV.sliceExists(slice_name):
      return "ready"
    else:
      return "configuring"
  except Exception, e:
    return "failed"
コード例 #35
0
def getSliverStatus(sliver_urn):
    try:
        slice_name = GeniDB.getFlowvisorSliceName(sliver_urn=sliver_urn)
        if FV.sliceExists(slice_name):
            return "ready"
        else:
            return "configuring"
    except Exception, e:
        return "failed"
コード例 #36
0
ファイル: auto.py プロジェクト: dana-i2cat/felix
  def expireSlivers (self):
    now = _asUTC(datetime.datetime.utcnow())
    exc_stack = []
    expired_slivers = []

    try:
      slivers = GeniDB.getExpiredSliverList(now)
      for sliver in slivers:
        try:
          data = GeniDB.getSliverData(sliver["sliver_urn"], True)

          TokenVerifier.checkToken("expire-sliver", sliver["sliver_urn"])
          foam.geni.lib.deleteSliver(sliver_urn = sliver["sliver_urn"])

          foam.task.emailExpireSliver(data)
          expired_slivers.append(data["sliver_urn"])
        except TokenError, e:
          exc_stack.append(jsonify({"exception" : traceback.format_exc()}))
      return jsonify({"expired" : expired_slivers})
コード例 #37
0
ファイル: auto.py プロジェクト: dana-i2cat/felix
 def emailPendingQueue (self):
   try:
     lines = []
     pending_list = GeniDB.getSliverList(False, None)
     for sliver in pending_list:
       sobj = GeniDB.getSliverObj(sliver["sliver_urn"])
       lines.append("Sliver URN: %s" % sobj.getURN())
       lines.append("     User: %s [%s]" % (sobj.getEmail(), sobj.getUserURN()))
       lines.append("")
     if lines:
       self._log.info("[Daily Queue] Sending email for %d sliver(s)" % (len(lines)/3))
       queue = "\n".join(lines)
       foam.task.emailPendingQueue({"pending-queue" : queue})
       return jsonify(None)
     self._log.info("[Daily Queue] No pending slivers to email")
     return jsonify(None)
   except Exception, e:
     self._log.exception("Exception")
     return jsonify(None, code = 2, msg  = traceback.format_exc())
コード例 #38
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def getFVSliceName (self):
   if not request.json:
     return
   try:
     self.validate(request.json, [("slice_urn", (unicode,str))])
     name = GeniDB.getFlowvisorSliceName(request.json["slice_urn"])
     return jsonify({"name" : name})
   except JSONValidationError, e:
     jd = e.__json__()
     return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #39
0
ファイル: lib.py プロジェクト: HalasNet/felix
  def emailCheck (self, now):
    tdw = datetime.timedelta(7)
    tdd = datetime.timedelta(hours=30)

    exp = self.getExpiration()
    if not self.getEmailStatus("day"):
      if now + tdd > exp:
        foam.task.emailSliverExpDay(GeniDB.getSliverData(self.__urn, True))
        self.setEmailStatus("day")
        self.setEmailStatus("week")
        self.store()
        return (self.__urn, 1)
    if not self.getEmailStatus("week"):
      if now + tdw > exp:
        foam.task.emailSliverExpWeek(GeniDB.getSliverData(self.__urn, True))
        self.setEmailStatus("week")
        self.store()
        return (self.__urn, 2)
    return (self.__urn, 0)
コード例 #40
0
ファイル: legacyexpedientapi.py プロジェクト: HalasNet/felix
  def priv_DeleteSliver(self, slice_urn, credentials, options=None):
    try:
      #if CredVerifier.checkValid(credentials, "deletesliver", slice_urn):
      if True:
        self.recordAction("deletesliver", credentials, slice_urn)
        if GeniDB.getSliverURN(slice_urn) is None:
          raise Fault("DeleteSliver", "Sliver for slice URN (%s) does not exist" % (slice_urn))
          return self.errorResult(12, "") #not sure if this is needed
        sliver_urn = GeniDB.getSliverURN(slice_urn)
        data = GeniDB.getSliverData(sliver_urn, True)
        foam.geni.lib.deleteSliver(sliver_urn = sliver_urn)
        foam.task.emailGAPIDeleteSliver(data)
        return self.successResult(True)
      return self.successResult(False)
		
    except UnknownSlice, x:
      self._log.info("Attempt to delete unknown sliver for slice URN %s" % (slice_urn))
      x._foam_logged = True
      raise x 
コード例 #41
0
  def pub_DeleteSliver (self, slice_urn, credentials):
    try:
      if CredVerifier.checkValid(credentials, "deletesliver", slice_urn):
        self.recordAction("deletesliver", credentials, slice_urn)
        if GeniDB.getSliverURN(slice_urn) is None:
          raise Fault("DeleteSliver", "Sliver for slice URN (%s) does not exist" % (slice_urn))

        sliver_urn = GeniDB.getSliverURN(slice_urn)
        data = GeniDB.getSliverData(sliver_urn, True)

        foam.geni.lib.deleteSliver(sliver_urn = sliver_urn)

        foam.task.emailGAPIDeleteSliver(data)

        return True
      return False
    except UnknownSlice, x:
      self._log.info("Attempt to delete unknown sliver for slice URN %s" % (slice_urn))
      x._foam_logged = True
      raise x
コード例 #42
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
  def rejectSliver (self):
    if not request.json:
      return
    try:
      self.validate(request.json, [("sliver_urn", (unicode,str))])
      slice_name = GeniDB.getFlowvisorSliceName(sliver_urn=request.json["sliver_urn"])
      sobj = GeniDB.getSliverObj(request.json["sliver_urn"])

      data = GeniDB.getSliverData(sobj.getURN(), True)

      GeniDB.setSliverStatus(request.json["sliver_urn"], False)
      if FV.sliceExists(slice_name):
        FV.deleteSlice(slice_name)

      foam.task.emailRejectSliver(data)

      return jsonify(None)
    except JSONValidationError, e:
      jd = e.__json__()
      return jsonify(jd, code = 1, msg = jd["exception"])
コード例 #43
0
ファイル: auto.py プロジェクト: pentikousis/C-BAS-framework
    def expireSlivers(self):
        now = _asUTC(datetime.datetime.utcnow())
        exc_stack = []
        expired_slivers = []

        try:
            slivers = GeniDB.getExpiredSliverList(now)
            for sliver in slivers:
                try:
                    data = GeniDB.getSliverData(sliver["sliver_urn"], True)

                    TokenVerifier.checkToken("expire-sliver",
                                             sliver["sliver_urn"])
                    foam.geni.lib.deleteSliver(sliver_urn=sliver["sliver_urn"])

                    foam.task.emailExpireSliver(data)
                    expired_slivers.append(data["sliver_urn"])
                except TokenError, e:
                    exc_stack.append(
                        jsonify({"exception": traceback.format_exc()}))
            return jsonify({"expired": expired_slivers})
コード例 #44
0
ファイル: auto.py プロジェクト: pentikousis/C-BAS-framework
 def emailPendingQueue(self):
     try:
         lines = []
         pending_list = GeniDB.getSliverList(False, None)
         for sliver in pending_list:
             sobj = GeniDB.getSliverObj(sliver["sliver_urn"])
             lines.append("Sliver URN: %s" % sobj.getURN())
             lines.append("     User: %s [%s]" %
                          (sobj.getEmail(), sobj.getUserURN()))
             lines.append("")
         if lines:
             self._log.info("[Daily Queue] Sending email for %d sliver(s)" %
                            (len(lines) / 3))
             queue = "\n".join(lines)
             foam.task.emailPendingQueue({"pending-queue": queue})
             return jsonify(None)
         self._log.info("[Daily Queue] No pending slivers to email")
         return jsonify(None)
     except Exception, e:
         self._log.exception("Exception")
         return jsonify(None, code=2, msg=traceback.format_exc())
コード例 #45
0
    def emailCheck(self, now):
        tdw = datetime.timedelta(7)
        tdd = datetime.timedelta(hours=30)

        exp = self.getExpiration()
        if not self.getEmailStatus("day"):
            if now + tdd > exp:
                foam.task.emailSliverExpDay(
                    GeniDB.getSliverData(self.__urn, True))
                self.setEmailStatus("day")
                self.setEmailStatus("week")
                self.store()
                return (self.__urn, 1)
        if not self.getEmailStatus("week"):
            if now + tdw > exp:
                foam.task.emailSliverExpWeek(
                    GeniDB.getSliverData(self.__urn, True))
                self.setEmailStatus("week")
                self.store()
                return (self.__urn, 2)
        return (self.__urn, 0)
コード例 #46
0
 def pub_SliverStatus (self, slice_urn, credentials):
   try:
     if CredVerifier.checkValid(credentials, "sliverstatus", slice_urn):
       self.recordAction("sliverstatus", credentials, slice_urn)
       result = {}
       sliver_urn = GeniDB.getSliverURN(slice_urn)
       if not sliver_urn:
         raise Fault("SliverStatus", "Sliver for slice URN (%s) does not exist" % (slice_urn))
       sdata = GeniDB.getSliverData(sliver_urn, True)
       status = foam.geni.lib.getSliverStatus(sliver_urn)
       result["geni_urn"] = sliver_urn
       result["geni_status"] = status
       result["geni_resources"] = [{"geni_urn" : sliver_urn, "geni_status": status, "geni_error" : ""}]
       result["foam_status"] = sdata["status"]
       result["foam_expires"] = sdata["expiration"]
       result["foam_pend_reason"] = sdata["pend_reason"]
       return result
     return False
   except UnknownSlice, x:
     self._log.info("Attempt to get status on unknown sliver for slice %s" % (slice_urn))
     x._foam_logged = True
     raise x
コード例 #47
0
ファイル: admin.py プロジェクト: pentikousis/C-BAS-framework
 def gapi_DeleteSliver(self, slice_urn, credentials, options=None):
   #GENI API imports
   from foam.geni.db import GeniDB, UnknownSlice, UnknownNode
   import foam.geni.approval
   import foam.geni.ofeliaapproval
   import sfa
   try:
     if True:
       #self.recordAction("deletesliver", credentials, slice_urn)
       if GeniDB.getSliverURN(slice_urn) is None:
         raise Fault("DeleteSliver", "Sliver for slice URN (%s) does not exist" % (slice_urn))
         return self.errorResult(12, "") #not sure if this is needed
       sliver_urn = GeniDB.getSliverURN(slice_urn)
       data = GeniDB.getSliverData(sliver_urn, True)
       foam.geni.lib.deleteSliver(sliver_urn = sliver_urn)
       foam.task.emailGAPIDeleteSliver(data)
       return self.successResult(True)
     return self.successResult(False)	
   except UnknownSlice, x:
     self._log.info("Attempt to delete unknown sliver for slice URN %s" % (slice_urn))
     x._foam_logged = True
     raise x 
コード例 #48
0
def createSliver(slice_urn, credentials, rspec, user_info):
    flog = logging.getLogger('foam')

    if GeniDB.sliceExists(slice_urn):
        raise DuplicateSliver(slice_urn)

    creds = CredVerifier.fromStrings(credentials, "createsliver", slice_urn)
    try:
        s = StringIO(rspec)
        rspec_dom = ET.parse(s)
    except Exception, exc:
        flog.exception("XML rspec parsing error")
        raise RspecParseError(slice_urn, str(exc))