RMR params payload points to params msgbuf. Make sure that freed memory is not used
[ric-plt/submgr.git] / pkg / control / control.go
index 52571aa..35e39f4 100755 (executable)
@@ -23,13 +23,12 @@ import (
        "fmt"
        "gerrit.o-ran-sc.org/r/ric-plt/e2ap/pkg/e2ap"
        rtmgrclient "gerrit.o-ran-sc.org/r/ric-plt/submgr/pkg/rtmgr_client"
-       rtmgrhandle "gerrit.o-ran-sc.org/r/ric-plt/submgr/pkg/rtmgr_client/handle"
+       "gerrit.o-ran-sc.org/r/ric-plt/submgr/pkg/xapptweaks"
+       "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/models"
        "gerrit.o-ran-sc.org/r/ric-plt/xapp-frame/pkg/xapp"
        httptransport "github.com/go-openapi/runtime/client"
        "github.com/go-openapi/strfmt"
        "github.com/spf13/viper"
-       "math/rand"
-       "sync"
        "time"
 )
 
@@ -37,18 +36,38 @@ import (
 //
 //-----------------------------------------------------------------------------
 
-var subReqTime time.Duration = 5 * time.Second
-var subDelReqTime time.Duration = 5 * time.Second
-var maxSubReqTryCount uint64 = 2    // Initial try + retry
-var maxSubDelReqTryCount uint64 = 2 // Initial try + retry
+func idstring(err error, entries ...fmt.Stringer) string {
+       var retval string = ""
+       var filler string = ""
+       for _, entry := range entries {
+               retval += filler + entry.String()
+               filler = " "
+       }
+       if err != nil {
+               retval += filler + "err(" + err.Error() + ")"
+               filler = " "
+
+       }
+       return retval
+}
+
+//-----------------------------------------------------------------------------
+//
+//-----------------------------------------------------------------------------
+
+var e2tSubReqTimeout time.Duration = 5 * time.Second
+var e2tSubDelReqTime time.Duration = 5 * time.Second
+var e2tMaxSubReqTryCount uint64 = 2    // Initial try + retry
+var e2tMaxSubDelReqTryCount uint64 = 2 // Initial try + retry
+
+var e2tRecvMsgTimeout time.Duration = 5 * time.Second
 
 type Control struct {
-       e2ap         *E2ap
-       registry     *Registry
-       tracker      *Tracker
-       timerMap     *TimerMap
-       rmrSendMutex sync.Mutex
-       msgCounter   uint64
+       xapptweaks.XappWrapper
+       e2ap     *E2ap
+       registry *Registry
+       tracker  *Tracker
+       //subscriber *xapp.Subscriber
 }
 
 type RMRMeid struct {
@@ -57,638 +76,547 @@ type RMRMeid struct {
        RanName string
 }
 
-var seedSN uint16
-
-const (
-       CREATE Action = 0
-       MERGE  Action = 1
-       NONE   Action = 2
-       DELETE Action = 3
-)
-
 func init() {
        xapp.Logger.Info("SUBMGR")
        viper.AutomaticEnv()
        viper.SetEnvPrefix("submgr")
        viper.AllowEmptyEnv(true)
-       seedSN = uint16(viper.GetInt("seed_sn"))
-       if seedSN == 0 {
-               rand.Seed(time.Now().UnixNano())
-               seedSN = uint16(rand.Intn(65535))
-       }
-       if seedSN > 65535 {
-               seedSN = 0
-       }
-       xapp.Logger.Info("SUBMGR: Initial Sequence Number: %v", seedSN)
 }
 
 func NewControl() *Control {
 
        transport := httptransport.New(viper.GetString("rtmgr.HostAddr")+":"+viper.GetString("rtmgr.port"), viper.GetString("rtmgr.baseUrl"), []string{"http"})
-       client := rtmgrclient.New(transport, strfmt.Default)
-       handle := rtmgrhandle.NewProvideXappSubscriptionHandleParamsWithTimeout(10 * time.Second)
-       deleteHandle := rtmgrhandle.NewDeleteXappSubscriptionHandleParamsWithTimeout(10 * time.Second)
-       rtmgrClient := RtmgrClient{client, handle, deleteHandle}
+       rtmgrClient := RtmgrClient{rtClient: rtmgrclient.New(transport, strfmt.Default)}
 
        registry := new(Registry)
-       registry.Initialize(seedSN)
+       registry.Initialize()
        registry.rtmgrClient = &rtmgrClient
 
        tracker := new(Tracker)
        tracker.Init()
 
-       timerMap := new(TimerMap)
-       timerMap.Init()
+       //subscriber := xapp.NewSubscriber(viper.GetString("subscription.host"), viper.GetInt("subscription.timeout"))
+
+       c := &Control{e2ap: new(E2ap),
+               registry: registry,
+               tracker:  tracker,
+               //subscriber: subscriber,
+       }
+       c.XappWrapper.Init("")
+       go xapp.Subscription.Listen(c.SubscriptionHandler, c.QueryHandler, c.SubscriptionDeleteHandler)
+       //go c.subscriber.Listen(c.SubscriptionHandler, c.QueryHandler)
+       return c
+}
 
-       return &Control{e2ap: new(E2ap),
-               registry:   registry,
-               tracker:    tracker,
-               timerMap:   timerMap,
-               msgCounter: 0,
+func (c *Control) ReadyCB(data interface{}) {
+       if c.Rmr == nil {
+               c.Rmr = xapp.Rmr
        }
 }
 
 func (c *Control) Run() {
+       xapp.SetReadyCB(c.ReadyCB, nil)
        xapp.Run(c)
 }
 
-func (c *Control) rmrSendRaw(desc string, params *RMRParams) (err error) {
-
-       xapp.Logger.Info("%s: %s", desc, params.String())
-       status := false
-       i := 1
-       for ; i <= 10 && status == false; i++ {
-               c.rmrSendMutex.Lock()
-               status = xapp.Rmr.Send(params.RMRParams, false)
-               c.rmrSendMutex.Unlock()
-               if status == false {
-                       xapp.Logger.Info("rmr.Send() failed. Retry count %d, %s", i, params.String())
-                       time.Sleep(500 * time.Millisecond)
-               }
-       }
-       if status == false {
-               err = fmt.Errorf("rmr.Send() failed. Retry count %d, %s", i, params.String())
-               xapp.Logger.Error("%s: %s", desc, err.Error())
-               xapp.Rmr.Free(params.Mbuf)
-       }
-       return
+//-------------------------------------------------------------------
+//
+//-------------------------------------------------------------------
+func (c *Control) SubscriptionHandler(stype models.SubscriptionType, params interface{}) (*models.SubscriptionResponse, error) {
+       /*
+          switch p := params.(type) {
+          case *models.ReportParams:
+              trans := c.tracker.NewXappTransaction(NewRmrEndpoint(p.ClientEndpoint),"" , 0, &xapp.RMRMeid{RanName: p.Meid})
+              if trans == nil {
+                    xapp.Logger.Error("XAPP-SubReq: %s", idstring(fmt.Errorf("transaction not created"), params))
+                    return
+              }
+              defer trans.Release()
+          case *models.ControlParams:
+          case *models.PolicyParams:
+          }
+       */
+       return &models.SubscriptionResponse{}, fmt.Errorf("Subscription rest interface not implemented")
+}
+
+func (c *Control) SubscriptionDeleteHandler(string) error {
+       return fmt.Errorf("Subscription rest interface not implemented")
 }
 
-func (c *Control) rmrSend(desc string, subs *Subscription, trans *Transaction) (err error) {
-       params := &RMRParams{&xapp.RMRParams{}}
+func (c *Control) QueryHandler() (models.SubscriptionList, error) {
+       return c.registry.QueryHandler()
+}
+
+//-------------------------------------------------------------------
+//
+//-------------------------------------------------------------------
+
+func (c *Control) rmrSendToE2T(desc string, subs *Subscription, trans *TransactionSubs) (err error) {
+       params := xapptweaks.NewParams(nil)
        params.Mtype = trans.GetMtype()
-       params.SubId = int(subs.GetSubId())
+       params.SubId = int(subs.GetReqId().InstanceId)
        params.Xid = ""
        params.Meid = subs.GetMeid()
        params.Src = ""
        params.PayloadLen = len(trans.Payload.Buf)
        params.Payload = trans.Payload.Buf
        params.Mbuf = nil
-
-       return c.rmrSendRaw(desc, params)
+       xapp.Logger.Info("MSG to E2T: %s %s %s", desc, trans.String(), params.String())
+       return c.RmrSend(params, 5)
 }
 
-func (c *Control) rmrReplyToSender(desc string, subs *Subscription, trans *Transaction) (err error) {
-       params := &RMRParams{&xapp.RMRParams{}}
+func (c *Control) rmrSendToXapp(desc string, subs *Subscription, trans *TransactionXapp) (err error) {
+
+       params := xapptweaks.NewParams(nil)
        params.Mtype = trans.GetMtype()
-       params.SubId = int(subs.GetSubId())
+       params.SubId = int(subs.GetReqId().InstanceId)
        params.Xid = trans.GetXid()
        params.Meid = trans.GetMeid()
        params.Src = ""
        params.PayloadLen = len(trans.Payload.Buf)
        params.Payload = trans.Payload.Buf
        params.Mbuf = nil
-
-       return c.rmrSendRaw(desc, params)
+       xapp.Logger.Info("MSG to XAPP: %s %s %s", desc, trans.String(), params.String())
+       return c.RmrSend(params, 5)
 }
 
 func (c *Control) Consume(params *xapp.RMRParams) (err error) {
-       xapp.Rmr.Free(params.Mbuf)
-       params.Mbuf = nil
-       msg := &RMRParams{params}
-       c.msgCounter++
+       msg := xapptweaks.NewParams(params)
+       if c.Rmr == nil {
+               err = fmt.Errorf("Rmr object nil can handle %s", msg.String())
+               xapp.Logger.Error("%s", err.Error())
+               return
+       }
+       c.CntRecvMsg++
+
+       defer c.Rmr.Free(msg.Mbuf)
+
+       // xapp-frame might use direct access to c buffer and
+       // when msg.Mbuf is freed, someone might take it into use
+       // and payload data might be invalid inside message handle function
+       //
+       // subscriptions won't load system a lot so there is no
+       // real performance hit by cloning buffer into new go byte slice
+       cPay := append(msg.Payload[:0:0], msg.Payload...)
+       msg.Payload = cPay
+       msg.PayloadLen = len(cPay)
+
        switch msg.Mtype {
-       case xapp.RICMessageTypes["RIC_SUB_REQ"]:
-               go c.handleSubscriptionRequest(msg)
-       case xapp.RICMessageTypes["RIC_SUB_RESP"]:
-               go c.handleSubscriptionResponse(msg)
-       case xapp.RICMessageTypes["RIC_SUB_FAILURE"]:
-               go c.handleSubscriptionFailure(msg)
-       case xapp.RICMessageTypes["RIC_SUB_DEL_REQ"]:
-               go c.handleSubscriptionDeleteRequest(msg)
-       case xapp.RICMessageTypes["RIC_SUB_DEL_RESP"]:
-               go c.handleSubscriptionDeleteResponse(msg)
-       case xapp.RICMessageTypes["RIC_SUB_DEL_FAILURE"]:
-               go c.handleSubscriptionDeleteFailure(msg)
+       case xapp.RIC_SUB_REQ:
+               go c.handleXAPPSubscriptionRequest(msg)
+       case xapp.RIC_SUB_RESP:
+               go c.handleE2TSubscriptionResponse(msg)
+       case xapp.RIC_SUB_FAILURE:
+               go c.handleE2TSubscriptionFailure(msg)
+       case xapp.RIC_SUB_DEL_REQ:
+               go c.handleXAPPSubscriptionDeleteRequest(msg)
+       case xapp.RIC_SUB_DEL_RESP:
+               go c.handleE2TSubscriptionDeleteResponse(msg)
+       case xapp.RIC_SUB_DEL_FAILURE:
+               go c.handleE2TSubscriptionDeleteFailure(msg)
        default:
                xapp.Logger.Info("Unknown Message Type '%d', discarding", msg.Mtype)
        }
-
-       return nil
+       return
 }
 
-func (c *Control) handleSubscriptionRequest(params *RMRParams) {
-       xapp.Logger.Info("SubReq from xapp: %s", params.String())
-
-       //
-       //
-       //
-       trans, err := c.tracker.TrackTransaction(NewRmrEndpoint(params.Src),
-               params.Xid,
-               params.Meid,
-               false,
-               true)
+//-------------------------------------------------------------------
+// handle from XAPP Subscription Request
+//------------------------------------------------------------------
+func (c *Control) handleXAPPSubscriptionRequest(params *xapptweaks.RMRParams) {
+       xapp.Logger.Info("MSG from XAPP: %s", params.String())
 
+       subReqMsg, err := c.e2ap.UnpackSubscriptionRequest(params.Payload)
        if err != nil {
-               xapp.Logger.Error("SubReq: %s, Dropping this msg. %s", err.Error(), params.String())
+               xapp.Logger.Error("XAPP-SubReq: %s", idstring(err, params))
                return
        }
 
-       //
-       //
-       //
-       trans.SubReqMsg, err = c.e2ap.UnpackSubscriptionRequest(params.Payload)
-       if err != nil {
-               xapp.Logger.Error("SubReq: %s Dropping this msg. %s", err.Error(), trans)
-               trans.Release()
+       trans := c.tracker.NewXappTransaction(xapptweaks.NewRmrEndpoint(params.Src), params.Xid, subReqMsg.RequestId.InstanceId, params.Meid)
+       if trans == nil {
+               xapp.Logger.Error("XAPP-SubReq: %s", idstring(fmt.Errorf("transaction not created"), params))
                return
        }
+       defer trans.Release()
 
-       //
-       //
-       //
-       subs, err := c.registry.ReserveSubscription(&trans.RmrEndpoint, trans.Meid)
+       err = c.tracker.Track(trans)
        if err != nil {
-               xapp.Logger.Error("SubReq: %s, Dropping this msg. %s", err.Error(), trans)
-               trans.Release()
+               xapp.Logger.Error("XAPP-SubReq: %s", idstring(err, trans))
                return
        }
 
-       err = subs.SetTransaction(trans)
+       //TODO handle subscription toward e2term inside AssignToSubscription / hide handleSubscriptionCreate in it?
+       subs, err := c.registry.AssignToSubscription(trans, subReqMsg)
        if err != nil {
-               xapp.Logger.Error("SubReq: %s, Dropping this msg. %s", err.Error(), trans)
-               subs.Release()
-               trans.Release()
+               xapp.Logger.Error("XAPP-SubReq: %s", idstring(err, trans))
                return
        }
 
-       trans.SubReqMsg.RequestId.Seq = uint32(subs.GetSubId())
-
-       //
-       // TODO: subscription create is in fact owned by subscription and not transaction.
-       //       Transaction is toward xapp while Subscription is toward ran.
-       //       In merge several xapps may wake transactions, while only one subscription
-       //       toward ran occurs -> subscription owns subscription creation toward ran
        //
-       //       This is intermediate solution while improving message handling
+       // Wake subs request
        //
-       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionRequest(trans.SubReqMsg)
-       if err != nil {
-               xapp.Logger.Error("SubReq: %s for trans %s", err.Error(), trans)
-               subs.Release()
-               trans.Release()
-               return
-       }
+       go c.handleSubscriptionCreate(subs, trans)
+       event, _ := trans.WaitEvent(0) //blocked wait as timeout is handled in subs side
 
-       c.rmrSend("SubReq: SubReq to E2T", subs, trans)
-
-       c.timerMap.StartTimer("RIC_SUB_REQ", int(subs.GetSubId()), subReqTime, FirstTry, c.handleSubscriptionRequestTimer)
-       xapp.Logger.Debug("SubReq: Debugging trans table = %v", c.tracker.transactionXappTable)
-       return
+       err = nil
+       if event != nil {
+               switch themsg := event.(type) {
+               case *e2ap.E2APSubscriptionResponse:
+                       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionResponse(themsg)
+                       if err == nil {
+                               trans.Release()
+                               c.rmrSendToXapp("", subs, trans)
+                               return
+                       }
+               case *e2ap.E2APSubscriptionFailure:
+                       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionFailure(themsg)
+                       if err == nil {
+                               c.rmrSendToXapp("", subs, trans)
+                       }
+               default:
+                       break
+               }
+       }
+       xapp.Logger.Info("XAPP-SubReq: failed %s", idstring(err, trans, subs))
+       //c.registry.RemoveFromSubscription(subs, trans, 5*time.Second)
 }
 
-func (c *Control) handleSubscriptionResponse(params *RMRParams) {
-       xapp.Logger.Info("SubResp from E2T: %s", params.String())
+//-------------------------------------------------------------------
+// handle from XAPP Subscription Delete Request
+//------------------------------------------------------------------
+func (c *Control) handleXAPPSubscriptionDeleteRequest(params *xapptweaks.RMRParams) {
+       xapp.Logger.Info("MSG from XAPP: %s", params.String())
 
-       //
-       //
-       //
-       SubRespMsg, err := c.e2ap.UnpackSubscriptionResponse(params.Payload)
+       subDelReqMsg, err := c.e2ap.UnpackSubscriptionDeleteRequest(params.Payload)
        if err != nil {
-               xapp.Logger.Error("SubDelReq: %s Dropping this msg. %s", err.Error(), params.String())
-               return
-       }
-
-       //
-       //
-       //
-       subs := c.registry.GetSubscription(uint16(SubRespMsg.RequestId.Seq))
-       if subs == nil && params.SubId > 0 {
-               subs = c.registry.GetSubscription(uint16(params.SubId))
-       }
-
-       if subs == nil {
-               xapp.Logger.Error("SubResp: Not valid subscription found payloadSeqNum: %d, SubId: %d. Dropping this msg. %s", SubRespMsg.RequestId.Seq, params.SubId, params.String())
+               xapp.Logger.Error("XAPP-SubDelReq %s", idstring(err, params))
                return
        }
-       xapp.Logger.Info("SubResp: subscription found payloadSeqNum: %d, SubId: %d", SubRespMsg.RequestId.Seq, subs.GetSubId())
 
-       //
-       //
-       //
-       trans := subs.GetTransaction()
+       trans := c.tracker.NewXappTransaction(xapptweaks.NewRmrEndpoint(params.Src), params.Xid, subDelReqMsg.RequestId.InstanceId, params.Meid)
        if trans == nil {
-               xapp.Logger.Error("SubResp: Unknown trans. Dropping this msg. SubId: %d", subs.GetSubId())
-               return
-       }
-
-       trans.SubRespMsg = SubRespMsg
-
-       //
-       //
-       //
-       c.timerMap.StopTimer("RIC_SUB_REQ", int(subs.GetSubId()))
-
-       responseReceived := trans.CheckResponseReceived()
-       if responseReceived == true {
-               // Subscription timer already received
+               xapp.Logger.Error("XAPP-SubDelReq: %s", idstring(fmt.Errorf("transaction not created"), params))
                return
        }
+       defer trans.Release()
 
-       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionResponse(trans.SubRespMsg)
+       err = c.tracker.Track(trans)
        if err != nil {
-               xapp.Logger.Error("SubResp: %s for trans %s", err.Error(), trans)
-               trans.Release()
+               xapp.Logger.Error("XAPP-SubReq: %s", idstring(err, trans))
                return
        }
 
-       subs.Confirmed()
-       trans.Release()
-       c.rmrReplyToSender("SubResp: SubResp to xapp", subs, trans)
-       return
-}
-
-func (c *Control) handleSubscriptionFailure(params *RMRParams) {
-       xapp.Logger.Info("SubFail from E2T: %s", params.String())
-
-       //
-       //
-       //
-       SubFailMsg, err := c.e2ap.UnpackSubscriptionFailure(params.Payload)
+       subs, err := c.registry.GetSubscriptionFirstMatch([]uint32{trans.GetSubId()})
        if err != nil {
-               xapp.Logger.Error("SubFail: %s Dropping this msg. %s", err.Error(), params.String())
+               xapp.Logger.Error("XAPP-SubDelReq: %s", idstring(err, trans))
                return
        }
 
        //
+       // Wake subs delete
        //
-       //
-       subs := c.registry.GetSubscription(uint16(SubFailMsg.RequestId.Seq))
-       if subs == nil && params.SubId > 0 {
-               subs = c.registry.GetSubscription(uint16(params.SubId))
-       }
+       go c.handleSubscriptionDelete(subs, trans)
+       trans.WaitEvent(0) //blocked wait as timeout is handled in subs side
 
-       if subs == nil {
-               xapp.Logger.Error("SubFail: Not valid subscription found payloadSeqNum: %d, SubId: %d. Dropping this msg. %s", SubFailMsg.RequestId.Seq, params.SubId, params.String())
-               return
-       }
-       xapp.Logger.Info("SubFail: subscription found payloadSeqNum: %d, SubId: %d", SubFailMsg.RequestId.Seq, subs.GetSubId())
+       xapp.Logger.Debug("XAPP-SubDelReq: Handling event %s ", idstring(nil, trans, subs))
 
-       //
-       //
-       //
-       trans := subs.GetTransaction()
-       if trans == nil {
-               xapp.Logger.Error("SubFail: Unknown trans. Dropping this msg. SubId: %d", subs.GetSubId())
-               return
-       }
-       trans.SubFailMsg = SubFailMsg
-
-       //
-       //
-       //
-       c.timerMap.StopTimer("RIC_SUB_REQ", int(subs.GetSubId()))
-
-       responseReceived := trans.CheckResponseReceived()
-       if err != nil {
-               return
-       }
-
-       if responseReceived == true {
-               // Subscription timer already received
-               return
-       }
-
-       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionFailure(trans.SubFailMsg)
+       // Whatever is received send ok delete response
+       subDelRespMsg := &e2ap.E2APSubscriptionDeleteResponse{}
+       subDelRespMsg.RequestId = subs.GetReqId().RequestId
+       subDelRespMsg.FunctionId = subs.SubReqMsg.FunctionId
+       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionDeleteResponse(subDelRespMsg)
        if err == nil {
-               c.rmrReplyToSender("SubFail: SubFail to xapp", subs, trans)
-               time.Sleep(3 * time.Second)
-       } else {
-               //TODO error handling improvement
-               xapp.Logger.Error("SubFail: %s for trans %s (continuing cleaning)", err.Error(), trans)
+               c.rmrSendToXapp("", subs, trans)
        }
 
-       trans.Release()
-       subs.Release()
-       return
+       //TODO handle subscription toward e2term insiged RemoveFromSubscription / hide handleSubscriptionDelete in it?
+       //c.registry.RemoveFromSubscription(subs, trans, 5*time.Second)
 }
 
-func (c *Control) handleSubscriptionRequestTimer(strId string, nbrId int, tryCount uint64) {
-       xapp.Logger.Info("SubReq timeout: subId: %v,  tryCount: %v", nbrId, tryCount)
-
-       subs := c.registry.GetSubscription(uint16(nbrId))
-       if subs == nil {
-               xapp.Logger.Error("SubReq timeout: Unknown payloadSeqNum. Dropping this msg. SubId: %v", nbrId)
-               return
-       }
+//-------------------------------------------------------------------
+// SUBS CREATE Handling
+//-------------------------------------------------------------------
+func (c *Control) handleSubscriptionCreate(subs *Subscription, parentTrans *TransactionXapp) {
+
+       trans := c.tracker.NewSubsTransaction(subs)
+       subs.WaitTransactionTurn(trans)
+       defer subs.ReleaseTransactionTurn(trans)
+       defer trans.Release()
+
+       xapp.Logger.Debug("SUBS-SubReq: Handling %s ", idstring(nil, trans, subs, parentTrans))
+
+       subRfMsg, valid := subs.GetCachedResponse()
+       if subRfMsg == nil && valid == true {
+
+               //
+               // In case of failure
+               // - make internal delete
+               // - in case duplicate cause, retry (currently max 1 retry)
+               //
+               maxRetries := uint64(1)
+               doRetry := true
+               for retries := uint64(0); retries <= maxRetries && doRetry; retries++ {
+                       doRetry = false
+
+                       event := c.sendE2TSubscriptionRequest(subs, trans, parentTrans)
+                       switch themsg := event.(type) {
+                       case *e2ap.E2APSubscriptionResponse:
+                               subRfMsg, valid = subs.SetCachedResponse(event, true)
+                       case *e2ap.E2APSubscriptionFailure:
+                               subRfMsg, valid = subs.SetCachedResponse(event, false)
+                               doRetry = true
+                               for _, item := range themsg.ActionNotAdmittedList.Items {
+                                       if item.Cause.Content != e2ap.E2AP_CauseContent_Ric || (item.Cause.Value != e2ap.E2AP_CauseValue_Ric_duplicate_action && item.Cause.Value != e2ap.E2AP_CauseValue_Ric_duplicate_event) {
+                                               doRetry = false
+                                               break
+                                       }
+                               }
+                               xapp.Logger.Info("SUBS-SubReq: internal delete and possible retry due event(%s) retry(%t,%d/%d) %s", typeofSubsMessage(event), doRetry, retries, maxRetries, idstring(nil, trans, subs, parentTrans))
+                               c.sendE2TSubscriptionDeleteRequest(subs, trans, parentTrans)
+                       default:
+                               xapp.Logger.Info("SUBS-SubReq: internal delete due event(%s) %s", typeofSubsMessage(event), idstring(nil, trans, subs, parentTrans))
+                               subRfMsg, valid = subs.SetCachedResponse(nil, false)
+                               c.sendE2TSubscriptionDeleteRequest(subs, trans, parentTrans)
+                       }
+               }
 
-       trans := subs.GetTransaction()
-       if trans == nil {
-               xapp.Logger.Error("SubReq timeout: Unknown trans. Dropping this msg. SubId: %v", subs.GetSubId())
-               return
+               xapp.Logger.Debug("SUBS-SubReq: Handling (e2t response %s) %s", typeofSubsMessage(subRfMsg), idstring(nil, trans, subs, parentTrans))
+       } else {
+               xapp.Logger.Debug("SUBS-SubReq: Handling (cached response %s) %s", typeofSubsMessage(subRfMsg), idstring(nil, trans, subs, parentTrans))
        }
 
-       responseReceived := trans.CheckResponseReceived()
-
-       if responseReceived == true {
-               // Subscription Response or Failure already received
-               return
+       //Now RemoveFromSubscription in here to avoid race conditions (mostly concerns delete)
+       if valid == false {
+               c.registry.RemoveFromSubscription(subs, parentTrans, 5*time.Second)
        }
+       parentTrans.SendEvent(subRfMsg, 0)
+}
 
-       if tryCount < maxSubReqTryCount {
-               xapp.Logger.Info("SubReq timeout: subs: %s trans: %s", subs, trans)
-
-               trans.RetryTransaction()
+//-------------------------------------------------------------------
+// SUBS DELETE Handling
+//-------------------------------------------------------------------
 
-               c.rmrSend("SubReq timeout: SubReq to E2T", subs, trans)
+func (c *Control) handleSubscriptionDelete(subs *Subscription, parentTrans *TransactionXapp) {
 
-               tryCount++
-               c.timerMap.StartTimer("RIC_SUB_REQ", int(subs.GetSubId()), subReqTime, tryCount, c.handleSubscriptionRequestTimer)
-               return
-       }
+       trans := c.tracker.NewSubsTransaction(subs)
+       subs.WaitTransactionTurn(trans)
+       defer subs.ReleaseTransactionTurn(trans)
+       defer trans.Release()
 
-       // Release CREATE transaction
-       trans.Release()
+       xapp.Logger.Debug("SUBS-SubDelReq: Handling %s", idstring(nil, trans, subs, parentTrans))
 
-       // Create DELETE transaction (internal and no messages toward xapp)
-       deltrans, err := c.tracker.TrackTransaction(&trans.RmrEndpoint,
-               trans.GetXid(),
-               trans.GetMeid(),
-               false,
-               false)
-
-       if err != nil {
-               xapp.Logger.Error("SubReq timeout: %s, Dropping this msg.", err.Error())
-               //TODO improve error handling. Important at least in merge
-               subs.Release()
-               return
+       subs.mutex.Lock()
+       if subs.valid && subs.EpList.HasEndpoint(parentTrans.GetEndpoint()) && subs.EpList.Size() == 1 {
+               subs.valid = false
+               subs.mutex.Unlock()
+               c.sendE2TSubscriptionDeleteRequest(subs, trans, parentTrans)
+       } else {
+               subs.mutex.Unlock()
        }
+       //Now RemoveFromSubscription in here to avoid race conditions (mostly concerns delete)
+       //  If parallel deletes ongoing both might pass earlier sendE2TSubscriptionDeleteRequest(...) if
+       //  RemoveFromSubscription locates in caller side (now in handleXAPPSubscriptionDeleteRequest(...))
+       c.registry.RemoveFromSubscription(subs, parentTrans, 5*time.Second)
+       parentTrans.SendEvent(nil, 0)
+}
 
-       deltrans.SubDelReqMsg = &e2ap.E2APSubscriptionDeleteRequest{}
-       deltrans.SubDelReqMsg.RequestId.Id = trans.SubReqMsg.RequestId.Id
-       deltrans.SubDelReqMsg.RequestId.Seq = uint32(subs.GetSubId())
-       deltrans.SubDelReqMsg.FunctionId = trans.SubReqMsg.FunctionId
-       deltrans.Mtype, deltrans.Payload, err = c.e2ap.PackSubscriptionDeleteRequest(deltrans.SubDelReqMsg)
+//-------------------------------------------------------------------
+// send to E2T Subscription Request
+//-------------------------------------------------------------------
+func (c *Control) sendE2TSubscriptionRequest(subs *Subscription, trans *TransactionSubs, parentTrans *TransactionXapp) interface{} {
+       var err error
+       var event interface{} = nil
+       var timedOut bool = false
+
+       subReqMsg := subs.SubReqMsg
+       subReqMsg.RequestId = subs.GetReqId().RequestId
+       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionRequest(subReqMsg)
        if err != nil {
-               xapp.Logger.Error("SubReq timeout: Packing SubDelReq failed. Err: %v", err)
-               //TODO improve error handling. Important at least in merge
-               deltrans.Release()
-               subs.Release()
-               return
+               xapp.Logger.Error("SUBS-SubReq: %s", idstring(err, trans, subs, parentTrans))
+               return event
        }
 
-       err = subs.SetTransaction(deltrans)
-       if err != nil {
-               xapp.Logger.Error("SubReq timeout: %s, Dropping this msg.", err.Error())
-               //TODO improve error handling. Important at least in merge
-               deltrans.Release()
-               return
+       for retries := uint64(0); retries < e2tMaxSubReqTryCount; retries++ {
+               desc := fmt.Sprintf("(retry %d)", retries)
+               c.rmrSendToE2T(desc, subs, trans)
+               event, timedOut = trans.WaitEvent(e2tSubReqTimeout)
+               if timedOut {
+                       continue
+               }
+               break
        }
-
-       c.rmrSend("SubReq timer: SubDelReq to E2T", subs, deltrans)
-       c.timerMap.StartTimer("RIC_SUB_DEL_REQ", int(subs.GetSubId()), subDelReqTime, FirstTry, c.handleSubscriptionDeleteRequestTimer)
-       return
+       xapp.Logger.Debug("SUBS-SubReq: Response handling event(%s) %s", typeofSubsMessage(event), idstring(nil, trans, subs, parentTrans))
+       return event
 }
 
-func (c *Control) handleSubscriptionDeleteRequest(params *RMRParams) {
-       xapp.Logger.Info("SubDelReq from xapp: %s", params.String())
-
-       //
-       //
-       //
-       trans, err := c.tracker.TrackTransaction(NewRmrEndpoint(params.Src),
-               params.Xid,
-               params.Meid,
-               false,
-               true)
+//-------------------------------------------------------------------
+// send to E2T Subscription Delete Request
+//-------------------------------------------------------------------
 
-       if err != nil {
-               xapp.Logger.Error("SubDelReq: %s, Dropping this msg. %s", err.Error(), params.String())
-               return
-       }
+func (c *Control) sendE2TSubscriptionDeleteRequest(subs *Subscription, trans *TransactionSubs, parentTrans *TransactionXapp) interface{} {
+       var err error
+       var event interface{}
+       var timedOut bool
 
-       //
-       //
-       //
-       trans.SubDelReqMsg, err = c.e2ap.UnpackSubscriptionDeleteRequest(params.Payload)
+       subDelReqMsg := &e2ap.E2APSubscriptionDeleteRequest{}
+       subDelReqMsg.RequestId = subs.GetReqId().RequestId
+       subDelReqMsg.FunctionId = subs.SubReqMsg.FunctionId
+       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionDeleteRequest(subDelReqMsg)
        if err != nil {
-               xapp.Logger.Error("SubDelReq: %s Dropping this msg. %s", err.Error(), trans)
-               trans.Release()
-               return
+               xapp.Logger.Error("SUBS-SubDelReq: %s", idstring(err, trans, subs, parentTrans))
+               return event
        }
 
-       //
-       //
-       //
-       subs := c.registry.GetSubscription(uint16(trans.SubDelReqMsg.RequestId.Seq))
-       if subs == nil && params.SubId > 0 {
-               subs = c.registry.GetSubscription(uint16(params.SubId))
+       for retries := uint64(0); retries < e2tMaxSubDelReqTryCount; retries++ {
+               desc := fmt.Sprintf("(retry %d)", retries)
+               c.rmrSendToE2T(desc, subs, trans)
+               event, timedOut = trans.WaitEvent(e2tSubDelReqTime)
+               if timedOut {
+                       continue
+               }
+               break
        }
+       xapp.Logger.Debug("SUBS-SubDelReq: Response handling event(%s) %s", typeofSubsMessage(event), idstring(nil, trans, subs, parentTrans))
+       return event
+}
 
-       if subs == nil {
-               xapp.Logger.Error("SubDelReq: Not valid subscription found payloadSeqNum: %d, SubId: %d. Dropping this msg. %s", trans.SubDelReqMsg.RequestId.Seq, params.SubId, trans)
-               trans.Release()
+//-------------------------------------------------------------------
+// handle from E2T Subscription Reponse
+//-------------------------------------------------------------------
+func (c *Control) handleE2TSubscriptionResponse(params *xapptweaks.RMRParams) {
+       xapp.Logger.Info("MSG from E2T: %s", params.String())
+       subRespMsg, err := c.e2ap.UnpackSubscriptionResponse(params.Payload)
+       if err != nil {
+               xapp.Logger.Error("MSG-SubResp %s", idstring(err, params))
                return
        }
-       xapp.Logger.Info("SubDelReq: subscription found payloadSeqNum: %d, SubId: %d. %s", trans.SubDelReqMsg.RequestId.Seq, params.SubId, trans)
-
-       err = subs.SetTransaction(trans)
+       subs, err := c.registry.GetSubscriptionFirstMatch([]uint32{subRespMsg.RequestId.InstanceId})
        if err != nil {
-               xapp.Logger.Error("SubDelReq: %s, Dropping this msg. %s", err.Error(), trans)
-               trans.Release()
+               xapp.Logger.Error("MSG-SubResp: %s", idstring(err, params))
                return
        }
-
-       //
-       // TODO: subscription delete is in fact owned by subscription and not transaction.
-       //       Transaction is toward xapp while Subscription is toward ran.
-       //       In merge several xapps may wake transactions, while only one subscription
-       //       toward ran occurs -> subscription owns subscription creation toward ran
-       //
-       //       This is intermediate solution while improving message handling
-       //
-       trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionDeleteRequest(trans.SubDelReqMsg)
-       if err != nil {
-               xapp.Logger.Error("SubDelReq: %s for trans %s", err.Error(), trans)
-               trans.Release()
+       trans := subs.GetTransaction()
+       if trans == nil {
+               err = fmt.Errorf("Ongoing transaction not found")
+               xapp.Logger.Error("MSG-SubResp: %s", idstring(err, params, subs))
                return
        }
-
-       subs.UnConfirmed()
-
-       c.rmrSend("SubDelReq: SubDelReq to E2T", subs, trans)
-
-       c.timerMap.StartTimer("RIC_SUB_DEL_REQ", int(subs.GetSubId()), subDelReqTime, FirstTry, c.handleSubscriptionDeleteRequestTimer)
+       sendOk, timedOut := trans.SendEvent(subRespMsg, e2tRecvMsgTimeout)
+       if sendOk == false {
+               err = fmt.Errorf("Passing event to transaction failed: sendOk(%t) timedOut(%t)", sendOk, timedOut)
+               xapp.Logger.Error("MSG-SubResp: %s", idstring(err, trans, subs))
+       }
        return
 }
 
-func (c *Control) handleSubscriptionDeleteResponse(params *RMRParams) (err error) {
-       xapp.Logger.Info("SubDelResp from E2T:%s", params.String())
-
-       //
-       //
-       //
-       SubDelRespMsg, err := c.e2ap.UnpackSubscriptionDeleteResponse(params.Payload)
+//-------------------------------------------------------------------
+// handle from E2T Subscription Failure
+//-------------------------------------------------------------------
+func (c *Control) handleE2TSubscriptionFailure(params *xapptweaks.RMRParams) {
+       xapp.Logger.Info("MSG from E2T: %s", params.String())
+       subFailMsg, err := c.e2ap.UnpackSubscriptionFailure(params.Payload)
        if err != nil {
-               xapp.Logger.Error("SubDelResp: %s Dropping this msg. %s", err.Error(), params.String())
+               xapp.Logger.Error("MSG-SubFail %s", idstring(err, params))
                return
        }
-
-       //
-       //
-       //
-       subs := c.registry.GetSubscription(uint16(SubDelRespMsg.RequestId.Seq))
-       if subs == nil && params.SubId > 0 {
-               subs = c.registry.GetSubscription(uint16(params.SubId))
-       }
-
-       if subs == nil {
-               xapp.Logger.Error("SubDelResp: Not valid subscription found payloadSeqNum: %d, SubId: %d. Dropping this msg. %s", SubDelRespMsg.RequestId.Seq, params.SubId, params.String())
+       subs, err := c.registry.GetSubscriptionFirstMatch([]uint32{subFailMsg.RequestId.InstanceId})
+       if err != nil {
+               xapp.Logger.Error("MSG-SubFail: %s", idstring(err, params))
                return
        }
-       xapp.Logger.Info("SubDelResp: subscription found payloadSeqNum: %d, SubId: %d", SubDelRespMsg.RequestId.Seq, subs.GetSubId())
-
-       //
-       //
-       //
        trans := subs.GetTransaction()
        if trans == nil {
-               xapp.Logger.Error("SubDelResp: Unknown trans. Dropping this msg. SubId: %d", subs.GetSubId())
+               err = fmt.Errorf("Ongoing transaction not found")
+               xapp.Logger.Error("MSG-SubFail: %s", idstring(err, params, subs))
                return
        }
-
-       trans.SubDelRespMsg = SubDelRespMsg
-
-       //
-       //
-       //
-       c.timerMap.StopTimer("RIC_SUB_DEL_REQ", int(subs.GetSubId()))
-
-       responseReceived := trans.CheckResponseReceived()
-       if responseReceived == true {
-               // Subscription Delete timer already received
-               return
+       sendOk, timedOut := trans.SendEvent(subFailMsg, e2tRecvMsgTimeout)
+       if sendOk == false {
+               err = fmt.Errorf("Passing event to transaction failed: sendOk(%t) timedOut(%t)", sendOk, timedOut)
+               xapp.Logger.Error("MSG-SubFail: %s", idstring(err, trans, subs))
        }
-
-       c.sendSubscriptionDeleteResponse("SubDelResp", trans, subs)
        return
 }
 
-func (c *Control) handleSubscriptionDeleteFailure(params *RMRParams) {
-       xapp.Logger.Info("SubDelFail from E2T:%s", params.String())
-
-       //
-       //
-       //
-       SubDelFailMsg, err := c.e2ap.UnpackSubscriptionDeleteFailure(params.Payload)
+//-------------------------------------------------------------------
+// handle from E2T Subscription Delete Response
+//-------------------------------------------------------------------
+func (c *Control) handleE2TSubscriptionDeleteResponse(params *xapptweaks.RMRParams) (err error) {
+       xapp.Logger.Info("MSG from E2T: %s", params.String())
+       subDelRespMsg, err := c.e2ap.UnpackSubscriptionDeleteResponse(params.Payload)
        if err != nil {
-               xapp.Logger.Error("SubDelFail: %s Dropping this msg. %s", err.Error(), params.String())
+               xapp.Logger.Error("MSG-SubDelResp: %s", idstring(err, params))
                return
        }
-
-       //
-       //
-       //
-       subs := c.registry.GetSubscription(uint16(SubDelFailMsg.RequestId.Seq))
-       if subs == nil && params.SubId > 0 {
-               subs = c.registry.GetSubscription(uint16(params.SubId))
-       }
-
-       if subs == nil {
-               xapp.Logger.Error("SubDelFail: Not valid subscription found payloadSeqNum: %d, SubId: %d. Dropping this msg. %s", SubDelFailMsg.RequestId.Seq, params.SubId, params.String())
+       subs, err := c.registry.GetSubscriptionFirstMatch([]uint32{subDelRespMsg.RequestId.InstanceId})
+       if err != nil {
+               xapp.Logger.Error("MSG-SubDelResp: %s", idstring(err, params))
                return
        }
-       xapp.Logger.Info("SubDelFail: subscription found payloadSeqNum: %d, SubId: %d", SubDelFailMsg.RequestId.Seq, subs.GetSubId())
-
-       //
-       //
-       //
        trans := subs.GetTransaction()
        if trans == nil {
-               xapp.Logger.Error("SubDelFail: Unknown trans. Dropping this msg. SubId: %d", subs.GetSubId())
+               err = fmt.Errorf("Ongoing transaction not found")
+               xapp.Logger.Error("MSG-SubDelResp: %s", idstring(err, params, subs))
                return
        }
-       trans.SubDelFailMsg = SubDelFailMsg
-
-       //
-       //
-       //
-       c.timerMap.StopTimer("RIC_SUB_DEL_REQ", int(subs.GetSubId()))
-
-       responseReceived := trans.CheckResponseReceived()
-       if responseReceived == true {
-               // Subscription Delete timer already received
-               return
+       sendOk, timedOut := trans.SendEvent(subDelRespMsg, e2tRecvMsgTimeout)
+       if sendOk == false {
+               err = fmt.Errorf("Passing event to transaction failed: sendOk(%t) timedOut(%t)", sendOk, timedOut)
+               xapp.Logger.Error("MSG-SubDelResp: %s", idstring(err, trans, subs))
        }
-
-       c.sendSubscriptionDeleteResponse("SubDelFail", trans, subs)
        return
 }
 
-func (c *Control) handleSubscriptionDeleteRequestTimer(strId string, nbrId int, tryCount uint64) {
-       xapp.Logger.Info("SubDelReq timeout: subId: %v, tryCount: %v", nbrId, tryCount)
-
-       subs := c.registry.GetSubscription(uint16(nbrId))
-       if subs == nil {
-               xapp.Logger.Error("SubDelReq timeout: Unknown payloadSeqNum. Dropping this msg. SubId: %v", nbrId)
+//-------------------------------------------------------------------
+// handle from E2T Subscription Delete Failure
+//-------------------------------------------------------------------
+func (c *Control) handleE2TSubscriptionDeleteFailure(params *xapptweaks.RMRParams) {
+       xapp.Logger.Info("MSG from E2T: %s", params.String())
+       subDelFailMsg, err := c.e2ap.UnpackSubscriptionDeleteFailure(params.Payload)
+       if err != nil {
+               xapp.Logger.Error("MSG-SubDelFail: %s", idstring(err, params))
                return
        }
-
-       trans := subs.GetTransaction()
-       if trans == nil {
-               xapp.Logger.Error("SubDelReq timeout: Unknown trans. Dropping this msg. SubId: %v", subs.GetSubId())
+       subs, err := c.registry.GetSubscriptionFirstMatch([]uint32{subDelFailMsg.RequestId.InstanceId})
+       if err != nil {
+               xapp.Logger.Error("MSG-SubDelFail: %s", idstring(err, params))
                return
        }
-
-       responseReceived := trans.CheckResponseReceived()
-       if responseReceived == true {
-               // Subscription Delete Response or Failure already received
+       trans := subs.GetTransaction()
+       if trans == nil {
+               err = fmt.Errorf("Ongoing transaction not found")
+               xapp.Logger.Error("MSG-SubDelFail: %s", idstring(err, params, subs))
                return
        }
-
-       if tryCount < maxSubDelReqTryCount {
-               // Set possible to handle new response for the subId
-               trans.RetryTransaction()
-               c.rmrSend("SubDelReq timeout: SubDelReq to E2T", subs, trans)
-               tryCount++
-               c.timerMap.StartTimer("RIC_SUB_DEL_REQ", int(subs.GetSubId()), subReqTime, tryCount, c.handleSubscriptionDeleteRequestTimer)
-               return
+       sendOk, timedOut := trans.SendEvent(subDelFailMsg, e2tRecvMsgTimeout)
+       if sendOk == false {
+               err = fmt.Errorf("Passing event to transaction failed: sendOk(%t) timedOut(%t)", sendOk, timedOut)
+               xapp.Logger.Error("MSG-SubDelFail: %s", idstring(err, trans, subs))
        }
-
-       c.sendSubscriptionDeleteResponse("SubDelReq(timer)", trans, subs)
        return
 }
 
-func (c *Control) sendSubscriptionDeleteResponse(desc string, trans *Transaction, subs *Subscription) {
-
-       if trans.ForwardRespToXapp == true {
-               //Always generate SubDelResp
-               trans.SubDelRespMsg = &e2ap.E2APSubscriptionDeleteResponse{}
-               trans.SubDelRespMsg.RequestId.Id = trans.SubDelReqMsg.RequestId.Id
-               trans.SubDelRespMsg.RequestId.Seq = uint32(subs.GetSubId())
-               trans.SubDelRespMsg.FunctionId = trans.SubDelReqMsg.FunctionId
-
-               var err error
-               trans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionDeleteResponse(trans.SubDelRespMsg)
-               if err == nil {
-                       c.rmrReplyToSender(desc+": SubDelResp to xapp", subs, trans)
-                       time.Sleep(3 * time.Second)
-               } else {
-                       //TODO error handling improvement
-                       xapp.Logger.Error("%s: %s for trans %s (continuing cleaning)", desc, err.Error(), trans)
-               }
+//-------------------------------------------------------------------
+//
+//-------------------------------------------------------------------
+func typeofSubsMessage(v interface{}) string {
+       if v == nil {
+               return "NIL"
+       }
+       switch v.(type) {
+       case *e2ap.E2APSubscriptionRequest:
+               return "SubReq"
+       case *e2ap.E2APSubscriptionResponse:
+               return "SubResp"
+       case *e2ap.E2APSubscriptionFailure:
+               return "SubFail"
+       case *e2ap.E2APSubscriptionDeleteRequest:
+               return "SubDelReq"
+       case *e2ap.E2APSubscriptionDeleteResponse:
+               return "SubDelResp"
+       case *e2ap.E2APSubscriptionDeleteFailure:
+               return "SubDelFail"
+       default:
+               return "Unknown"
        }
-
-       trans.Release()
-       subs.Release()
 }