id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,533,027
|
GameClasses.h
|
Bakkes_CPPRP/CPPRP/data/GameClasses.h
|
#pragma once
#include "NetworkData.h"
#include <string>
#include <stdint.h>
#define FIELD(...)
#define CLASS(...)
namespace CPPRP
{
namespace Engine
{
struct Object
{
virtual ~Object() {} //Makes it polymorphic
};
struct Actor : public Object
{
float DrawScale;
bool bCollideActors;
bool bCollideWorld;
bool bNetOwner;
struct ActorBase Base;
bool bBlockActors;
bool bHidden;
bool bTearOff;
struct Vector3I Location;
struct Rotator Rotation;
//Fields that aren't used (yet) but could probably be replicated
uint8_t Physics;
uint8_t RemoteRole;
uint8_t Role;
uint8_t ReplicatedCollisionType;
ActiveActor Owner;
bool bHardAttach;
ActiveActor Instigator;
Vector3I RelativeLocation;
Rotator RelativeRotation;
bool bRootMotionFromInterpCurve;
};
struct ReplicatedActor_ORS : public Actor
{
ActiveActor ReplicatedOwner;
};
struct Info : public Actor
{
};
struct ReplicationInfo : public Info
{
};
struct GameReplicationInfo : public ReplicationInfo
{
std::string ServerName;
struct ObjectTarget GameClass;
bool bStopCountDown;
bool bMatchIsOver;
bool bMatchHasBegun;
//Unused?
int RemainingTime;
int ElapsedTime;
int RemainingMinute;
int GoalScore;
int TimeLimit;
ActiveActor Winner;
};
struct Pawn : public Actor
{
struct ActiveActor PlayerReplicationInfo;
uint32_t HealthMax;
bool bIsCrouched;
//Controller Controller;
bool bIsWalking;
bool bSimulateGravity;
bool bCanSwatTurn;
bool bUsedByMatinee;
bool bRootMotionFromInterpCurve;
bool bFastAttachedMove;
uint8_t RemoteViewPitch;
float GroundSpeed;
float AirSpeed;
float AccelRate;
float JumpZ;
float AirControl;
float RootMotionInterpRate;
float RootMotionInterpCurrentTime;
Vector3I RootMotionInterpCurveLastValue;
};
struct PlayerReplicationInfo : public ReplicationInfo
{
struct ActiveActor Team;
bool bReadyToPlay;
std::string PlayerName;
std::string RemoteUserData;
bool bWaitingPlayer;
uint32_t Score;
uint32_t PlayerID;
bool bBot;
bool bIsSpectator;
bool bTimedOut;
bool bAdmin;
bool bIsInactive;
bool bOnlySpectator;
uint8_t Ping;
OnlineID UniqueId;
//Unused
uint32_t Deaths;
uint8_t TTSSpeaker;
bool bOutOfLives;
bool bFromPreviousLevel;
//PRIRemoteUserData RemoteUserData
};
struct TeamInfo : public ReplicationInfo
{
uint32_t Score;
//Unused
//std::string TeamName;
//int TeamIndex;
};
struct WorldInfo : public Info
{
float WorldGravityZ;
float TimeDilation;
bool bHighPriorityLoading;
ActiveActor Pauser; //Is of type PlayerReplicationInfo
//MusicTrackStruct ReplicatedMusicTrack;
};
struct DynamicSMActor : public Actor
{
//class UStaticMesh* ReplicatedMesh; // 0x01F0 (0x0004) [0x0000000000002020] ( CPF_Net | CPF_Transient )
//class UMaterialInterface* ReplicatedMaterial0; // 0x01F4 (0x0004) [0x0000000000000020] ( CPF_Net )
//class UMaterialInterface* ReplicatedMaterial1; // 0x01F8 (0x0004) [0x0000000000000020] ( CPF_Net )
//class UMaterialInterface* ReplicatedMaterial2; // 0x01FC (0x0004) [0x0000000000000020] ( CPF_Net )
//class UMaterialInterface* ReplicatedMaterial3; // 0x0200 (0x0004) [0x0000000000000020] ( CPF_Net )
ObjectTarget ReplicatedMesh; // 0x01F0 (0x0004) [0x0000000000002020] ( CPF_Net | CPF_Transient )
ObjectTarget ReplicatedMaterial0; // 0x01F4 (0x0004) [0x0000000000000020] ( CPF_Net )
ObjectTarget ReplicatedMaterial1; // 0x01F8 (0x0004) [0x0000000000000020] ( CPF_Net )
ObjectTarget ReplicatedMaterial2; // 0x01FC (0x0004) [0x0000000000000020] ( CPF_Net )
ObjectTarget ReplicatedMaterial3; // 0x0200 (0x0004) [0x0000000000000020] ( CPF_Net )
bool bForceStaticDecals; // 0x0204 (0x0004) [0x0000000000000020] [0x00000001] ( CPF_Net )
Vector3 ReplicatedMeshTranslation; // 0x0208 (0x000C) [0x0000000000000020] ( CPF_Net )
Rotator ReplicatedMeshRotation; // 0x0214 (0x000C) [0x0000000000000020] ( CPF_Net )
Vector3 ReplicatedMeshScale3D; // 0x0220 (0x000C) [0x0000000000000020] ( CPF_Net )
};
//Currently only used in workshop map replays
struct KActor : public DynamicSMActor
{
bool bWakeOnLevelStart;
RigidBodyState RBState;
Vector3 ReplicatedDrawScale3D;
};
};
namespace ProjectX
{
struct GRI_X : public Engine::GameReplicationInfo
{
std::string MatchGUID;
std::string MatchGuid; //TODO? Logic to merge these two? (case changed in rl 2.21)
std::string ReplicatedServerRegion;
int ReplicatedGameMutatorIndex;
bool bGameStarted;
bool bGameEnded;
uint32_t ReplicatedGamePlaylist;
GameServer GameServerID;
struct Reservation Reservations; //is actually array of size 0x8, first 3 bits read is index of array i guess
};
struct NetModeReplicator_X : public Engine::ReplicationInfo
{
};
struct Pawn_X : public Engine::Pawn
{
};
struct PRI_X : public Engine::PlayerReplicationInfo
{
};
};
namespace TAGame
{
struct PRI_TA : public ProjectX::PRI_X
{
uint32_t MatchShots;
struct ActiveActor PersistentCamera;
struct SkillTier SkillTier;
bool bUsingBehindView;
uint32_t MatchAssists;
int RespawnTimeRemaining;
bool bOnlineLoadoutSet;
uint32_t MatchGoals;
struct ActiveActor ReplicatedGameEvent;
uint32_t TotalXP;
uint32_t MatchScore;
uint32_t MatchSaves;
uint32_t Title;
uint64_t ClubID;
int MaxTimeTillItem;
ActiveActor PickupTimer;
uint32_t MatchBreakoutDamage;
uint32_t BotProductName;
uint32_t BotBannerProductID;
bool bReady;
uint32_t SpectatorShortcut;
bool bUsingSecondaryCamera;
bool PlayerHistoryValid;
bool bIsInSplitScreen;
bool bMatchMVP;
struct RepStatTitle RepStatTitles;
bool bOnlineLoadoutsSet;
bool bUsingItems;
struct ReplicatedTitle PrimaryTitle;
bool bMatchAdmin;
bool bBusy;
bool bVoteToForfeitDisabled;
bool bUsingFreecam;
struct OnlineLoadout ClientLoadoutOnline;
uint8_t CameraYaw;
uint8_t CameraPitch;
uint8_t PawnType;
uint8_t ReplicatedWorstNetQualityBeyondLatency;
float SteeringSensitivity;
struct PartyLeader PartyLeader;
int TimeTillItem;
struct ClientLoadoutsOnline ClientLoadoutsOnline;
struct ClientLoadouts ClientLoadouts;
struct ClientLoadout ClientLoadout;
struct CameraSettings CameraSettings;
struct ReplicatedTitle SecondaryTitle;
struct HistoryKey PlayerHistoryKey;
bool bIdleBanned;
bool bIsDistracted;
//Unused
ActiveActor ReplacingBotPRI;
std::string CurrentVoiceRoom;
//PlayerReplicatedEventInfo_TA PREI
};
struct PRI_KnockOut_TA : public PRI_TA
{
int Knockouts;
int KnockoutDeaths;
int DamageCaused;
int Hits;
int Grabs;
int Blocks;
bool bIsActiveMVP;
};
struct RBActor_TA : public ProjectX::Pawn_X
{
struct ReplicatedRBState ReplicatedRBState;
bool bReplayActor;
bool bFrozen;
struct WeldedInfo WeldedInfo;
bool bIgnoreSyncing;
float MaxLinearSpeed;
float MaxAngularSpeed;
uint8_t TeleportCounter;
};
struct CarComponent_TA : public Engine::ReplicationInfo
{
struct ActiveActor Vehicle;
uint8_t ReplicatedActive;
float ReplicatedActivityTime;
};
struct CarComponent_AirActivate_TA : public CarComponent_TA
{
int AirActivateCount;
};
struct CarComponent_Jump_TA : public CarComponent_TA
{
};
struct CarComponent_DoubleJump_TA : public CarComponent_AirActivate_TA
{
struct Vector3I DoubleJumpImpulse;
};
struct CarComponent_DoubleJump_KO_TA : public CarComponent_DoubleJump_TA
{
};
struct CarComponent_Boost_TA : public CarComponent_AirActivate_TA
{
float RechargeDelay;
bool bUnlimitedBoost;
uint32_t UnlimitedBoostRefCount;
bool bNoBoost;
uint8_t ReplicatedBoostAmount;
ReplicatedBoostData ReplicatedBoost;
float RechargeRate;
float BoostModifier;
//unused
float StartBoostAmount;
float CurrentBoostAmount;
bool bRechargeGroundOnly;
};
struct CarComponent_Boost_KO_TA : public CarComponent_Boost_TA
{
};
struct CarComponent_Dodge_TA : public CarComponent_AirActivate_TA
{
struct Vector3I DodgeTorque;
struct Vector3I DodgeImpulse;
};
struct CarComponent_Dodge_KO_TA : public CarComponent_Dodge_TA
{
int32_t DodgeRotationCompressed;
};
struct CarComponent_FlipCar_TA : public CarComponent_TA
{
bool bFlipRight;
float FlipCarTime;
};
struct CarComponent_Torque_TA : public CarComponent_TA
{
float TorqueScale;
int32_t ReplicatedTorqueInput;
};
struct Ball_TA : public RBActor_TA
{
struct ActiveActor GameEvent;
struct ObjectTarget ReplicatedPhysMatOverride;
float ReplicatedBallGravityScale;
float ReplicatedBallScale;
unsigned char HitTeamNum;
float ReplicatedWorldBounceScale;
float ReplicatedAddedCarBounceScale;
struct ReplicatedExplosionData ReplicatedExplosionData;
float ReplicatedBallMaxLinearSpeedScale;
struct ReplicatedExplosionDataExtended ReplicatedExplosionDataExtended;
Vector3I MagnusCoefficient;
//Unused
bool bEndOfGameHidden;
//ObjectTarget ReplicatedBallMesh; //ObjectTarget or active actor, idk
};
struct Team_TA : public Engine::TeamInfo
{
struct LogoData LogoData;
struct ActiveActor GameEvent;
std::string CustomTeamName;
uint64_t ClubID;
int32_t Difficulty;
struct ClubColors ClubColors;
};
struct Team_Soccar_TA : public Team_TA
{
uint32_t GameScore;
};
struct BreakOutActor_Platform_TA : public Engine::Actor
{
struct DamageState DamageState;
};
struct SpecialPickup_TA : public CarComponent_TA
{
};
struct SpecialPickup_Targeted_TA : public SpecialPickup_TA
{
struct ActiveActor Targeted;
};
struct SpecialPickup_Tornado_TA : public SpecialPickup_TA
{
};
struct SpecialPickup_HauntedBallBeam_TA : public SpecialPickup_TA
{
};
struct SpecialPickup_BallVelcro_TA : public SpecialPickup_TA
{
bool bHit;
bool bBroken;
float AttachTime;
float BreakTime;
};
struct SpecialPickup_Rugby_TA : public SpecialPickup_TA
{
bool bBallWelded;
};
struct SpecialPickup_BallFreeze_TA : public SpecialPickup_Targeted_TA
{
float RepOrigSpeed;
};
struct SpecialPickup_Spring_TA : public SpecialPickup_Targeted_TA
{
};
struct SpecialPickup_BallCarSpring_TA : public SpecialPickup_Spring_TA
{
};
struct SpecialPickup_BallGravity_TA : public SpecialPickup_TA
{
};
struct SpecialPickup_GrapplingHook_TA : public SpecialPickup_Targeted_TA
{
};
struct SpecialPickup_BallLasso_TA : public SpecialPickup_GrapplingHook_TA
{
};
struct SpecialPickup_BoostOverride_TA : public SpecialPickup_Targeted_TA
{
};
struct SpecialPickup_Batarang_TA : public SpecialPickup_BallLasso_TA
{
};
struct SpecialPickup_HitForce_TA : public SpecialPickup_TA
{
};
struct SpecialPickup_Swapper_TA : public SpecialPickup_Targeted_TA
{
};
struct SpecialPickup_Football_TA : public SpecialPickup_TA
{
struct ActiveActor WeldedBall;
};
struct CrowdManager_TA : public Engine::ReplicationInfo
{
struct ActiveActor GameEvent;
struct ObjectTarget ReplicatedGlobalOneShotSound;
};
struct CrowdActor_TA : public Engine::ReplicationInfo
{
struct ActiveActor GameEvent;
struct ObjectTarget ReplicatedOneShotSound;
uint32_t ReplicatedRoundCountDownNumber;
uint32_t ReplicatedCountDownNumber;
float ModifiedNoise;
};
struct InMapScoreboard_TA : public Engine::Actor
{
};
struct Vehicle_TA : public RBActor_TA
{
unsigned char ReplicatedThrottle;
bool bReplicatedHandbrake;
bool bDriving;
unsigned char ReplicatedSteer;
bool bHasPostMatchCelebration;
//Unused
bool bPodiumMode;
};
struct Car_TA : public Vehicle_TA
{
struct ActiveActor AttachedPickup;
struct ActiveActor RumblePickups;
float AddedCarForceMultiplier;
float ReplicatedCarScale;
float AddedBallForceMultiplier;
struct TeamPaint TeamPaint;
struct ReplicatedDemolish ReplicatedDemolish;
struct ReplicatedDemolish2 ReplicatedDemolish_CustomFX;
struct DemolishDataGoalExplosion ReplicatedDemolishGoalExplosion;
struct ClubColors ClubColors;
};
struct Car_Season_TA : public Car_TA
{
};
struct Car_KnockOut_TA : public Car_TA
{
uint32_t ReplicatedStateName;
unsigned char ReplicatedStateChanged;
ImpulseData ReplicatedImpulse;
ActiveActor UsedAttackComponent;
};
struct CameraSettingsActor_TA : public Engine::ReplicationInfo
{
struct ActiveActor PRI;
bool bMouseCameraToggleEnabled;
bool bUsingSecondaryCamera;
bool bUsingBehindView;
struct CameraSettings ProfileSettings;
bool bUsingSwivel;
bool bUsingFreecam;
bool bHoldMouseCamera;
bool bResetCamera;
uint8_t CameraPitch;
uint8_t CameraYaw;
};
struct GRI_TA : public ProjectX::GRI_X
{
std::string NewDedicatedServerIP;
};
struct Ball_Breakout_TA : public Ball_TA
{
uint32_t DamageIndex;
struct AppliedDamage AppliedDamage;
unsigned char LastTeamTouch;
};
struct Ball_God_TA : public Ball_TA
{
float TargetSpeed;
};
struct VehiclePickup_TA : public Engine::ReplicationInfo
{
bool bNoPickup;
struct ReplicatedPickupData ReplicatedPickupData;
struct ReplicatedPickupData2 NewReplicatedPickupData;
};
struct VehiclePickup_Boost_TA : public VehiclePickup_TA
{
};
struct VehiclePickup_Item_TA : public VehiclePickup_TA
{
ActiveActor ReplicatedFXActorArchetype;
};
struct Ball_Haunted_TA : public Ball_TA
{
unsigned char DeactivatedGoalIndex;
bool bIsBallBeamed;
unsigned char ReplicatedBeamBrokenValue;
unsigned char LastTeamTouch;
unsigned char TotalActiveBeams;
};
struct GameEvent_TA : public Engine::ReplicationInfo
{
uint32_t ReplicatedRoundCountDownNumber;
struct ActiveActor ActivatorCar;
uint32_t ReplicatedGameStateTimeRemaining;
uint32_t ReplicatedStateName;
struct ObjectTarget MatchTypeClass;
float BotSkill;
bool bHasLeaveMatchPenalty;
bool bCanVoteToForfeit;
bool bAllowReadyUp;
struct GameMode GameMode;
struct ReplicatedStateIndex ReplicatedStateIndex; //Might actually just be an uint8_t??
struct ActiveActor GameOwner; //PRI_TA
bool bIsBotMatch;
uint64_t MatchStartEpoch;
//struct CustomMatchSettings MatchSettings;
};
struct GameEvent_Team_TA : public GameEvent_TA
{
uint32_t MaxTeamSize;
bool bForfeit;
bool bDisableMutingOtherTeam;
};
struct GameEvent_Soccar_TA : public GameEvent_Team_TA
{
bool bOverTime;
uint32_t GameTime;
struct ActiveActor MVP;
struct ActiveActor MatchWinner;
struct ActiveActor GameWinner;
struct ObjectTarget SubRulesArchetype;
uint32_t SecondsRemaining;
uint32_t RoundNum;
uint32_t SeriesLength;
struct ReplicatedMusicStringer ReplicatedMusicStinger;
bool bBallHasBeenHit;
bool bUnlimitedTime;
struct ReplicatedStatEvent ReplicatedStatEvent;
bool bShowIntroScene;
bool bClubMatch;
unsigned char ReplicatedScoredOnTeam;
bool bMatchEnded;
unsigned char ReplicatedServerPerformanceState;
uint32_t MaxScore;
};
struct GameEvent_KnockOut_TA : public GameEvent_Soccar_TA
{
int PlayerLives;
};
struct GameEvent_Breakout_TA : public GameEvent_Soccar_TA
{
};
struct GameEvent_Football_TA : public GameEvent_Soccar_TA
{
};
struct GameEvent_GodBall_TA : public GameEvent_Soccar_TA
{
};
struct GameEvent_Season_TA : public GameEvent_Soccar_TA
{
};
struct GameEvent_SoccarPrivate_TA : public GameEvent_Soccar_TA
{
struct PrivateMatchSettings MatchSettings;
};
struct GameEvent_SoccarSplitscreen_TA : public GameEvent_SoccarPrivate_TA
{
};
struct GameEvent_Tutorial_TA : public GameEvent_Soccar_TA
{
};
struct GameEvent_Tutorial_Goalie_TA : public GameEvent_Tutorial_TA
{
};
struct GameEvent_Tutorial_Striker_TA : public GameEvent_Tutorial_TA
{
};
struct GameEvent_GameEditor_TA : public GameEvent_Soccar_TA
{
};
struct GameEditor_Pawn_TA : public ProjectX::Pawn_X
{
};
struct GameEvent_TrainingEditor_TA : public GameEvent_GameEditor_TA
{
};
struct HauntedBallTrapTrigger_TA : public Engine::Actor
{
};
struct MaxTimeWarningData_TA : public Engine::ReplicatedActor_ORS
{
uint64_t EndGameEpochTime;
uint64_t EndGameWarningEpochTime;
};
struct RumblePickups_TA : public Engine::Actor
{
ActiveActor AttachedPickup;
int ConcurrentItemCount;
PickupInfo_TA PickupInfo;
};
struct PickupTimer_TA : public CarComponent_TA
{
int TimeTillItem;
int MaxTimeTillItem;
};
struct Cannon_TA : public Engine::Actor
{
float Pitch;
uint8_t FireCount;
};
struct Stunlock_TA : public Engine::Actor
{
ActiveActor Car;
float MaxStunTime;
float StunTimeRemaining;
};
struct PlayerStart_Platform_TA : public Engine::Actor
{
bool bActive;
};
};
}
| 17,688
|
C++
|
.h
| 623
| 24.614767
| 156
| 0.740175
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,028
|
NetworkData.h
|
Bakkes_CPPRP/CPPRP/data/NetworkData.h
|
#pragma once
#include <stdint.h>
#include <sstream>
#include <vector>
#include "CPPBitReader.h"
#include <variant>
/*
ParserAttributes:
Consume true/false ->
If on struct -> if false, don't generate parser. Must implement your own in NetworkDataParser.h
If on member -> needs to be true for non standard types that don't have a read<T> method in CPPBitReader
NumBits x -> declare if x != sizeof(type) * 8, for example when an uint8_t is used to store but only 3 bits need to be read from stream
EngineVersion x -> Only parse replay if engine version >= x
LicenseeVersion x -> Only parse replay if licensee version >= x
MaxBits x -> instead of reading set number of bits, will call CPPBitReader::get_bits_max(x);
std::vector<T> members always assume it can read a uint8_t member containing the size of vector, then fills it with reading T
std::shared_ptr<T> Parser needs to be specifically implemented to return a shared_ptr.
*/
#define __ParserAttribute__(...)
namespace CPPRP
{
__ParserAttribute__(Consume, false)
struct ReplicatedRBState
{
Quat rotation;
Vector3 position;
Vector3 linear_velocity;
Vector3 angular_velocity;
bool sleeping;
};
__ParserAttribute__(Consume, false)
struct GameServer
{
uint32_t GameServerID;
std::string GameServerIDString; //Replays after 29-11-2022 update use a string for this, before uses the uint64_t
};
struct LogoData
{
bool swap_colors;
uint32_t logo_id;
};
struct ActiveActor
{
bool active;
int32_t actor_id;
};
struct ObjectTarget
{
bool unknown;
int32_t object_index;
};
__ParserAttribute__(Consume, false)
struct Reservation
{
__ParserAttribute__(NumBits, 3)
uint8_t number;
OnlineID player_id;
std::string player_name;
uint8_t status;
};
// ReservationStatus_None = 0,
// ReservationStatus_Reserved = 1,
// ReservationStatus_Joining = 2,
// ReservationStatus_InGame = 3,
// ReservationStatus_MAX = 4
//Maybe its not version, but size instead? then fill array of size version
__ParserAttribute__(Consume, false)
struct ClientLoadout
{
uint8_t version;
uint32_t body;
uint32_t skin;
uint32_t wheels;
uint32_t boost;
uint32_t antenna;
uint32_t hat;
uint32_t unknown2;
uint32_t unknown3;
uint32_t engine_audio;
uint32_t trail;
uint32_t goal_explosion;
uint32_t banner;
uint32_t unknown4;
uint32_t unknown5;
uint32_t unknown6;
uint32_t unknown7;
};
struct CameraSettings
{
float FOV;
float height;
float pitch;
float distance;
float stiffness;
float swivelspeed;
__ParserAttribute__(EngineVersion, 868)
__ParserAttribute__(LicenseeVersion, 20)
float transitionspeed;
};
struct ReplicatedPickupData
{
bool unknown1; //some kind of flag?
int32_t actor_id; //instigator
bool picked_up;
};
struct ReplicatedPickupData2
{
bool unknown1;
int32_t actor_id; //instigator
uint8_t picked_up;
};
struct TeamPaint
{
uint8_t team_number;
uint8_t team_color_id;
uint8_t custom_color_id;
uint32_t team_finish_id;
uint32_t custom_finish_id;
};
struct ReplicatedDemolish
{
bool attacker_flag;
int32_t attacker_actor_id;
bool victim_flag;
int32_t victim_actor_id;
Vector3 attacker_velocity;
Vector3 victim_velocity;
};
struct ReplicatedDemolish2
{
bool custom_demo_flag;
int32_t custom_demo_id;
bool attacker_flag;
int32_t attacker_actor_id;
bool victim_flag;
int32_t victim_actor_id;
Vector3 attacker_velocity;
Vector3 victim_velocity;
};
//Actually extends ReplicatedDemolish but i don't think our preprocessor supports extending
//And we need to parse in reverse order (?)
struct DemolishDataGoalExplosion
{
bool goal_explosion_owner_flag;
int32_t goal_explosion_owner;
bool attacker_flag;
int32_t attacker_actor_id;
bool victim_flag;
int32_t victim_actor_id;
Vector3 attacker_velocity;
Vector3 victim_velocity;
};
struct ReplicatedMusicStringer
{
bool unknown1;
uint32_t object_index;
uint8_t trigger;
};
__ParserAttribute__(Consume, false)
struct GameMode
{
uint8_t gamemode;
};
struct ReplicatedStateIndex
{
__ParserAttribute__(MaxBits, 140)
uint32_t value;
};
struct PrivateMatchSettings
{
std::string mutators;
uint32_t map_name;
uint32_t max_player_count;
std::string game_name;
std::string password;
bool is_public;
};
__ParserAttribute__(Consume, false)
struct ProductAttribute
{
uint32_t class_index;
std::string class_name;
uint32_t value;
bool has_value;
bool unknown1;
virtual ~ProductAttribute() = default;
};
//__ParserAttribute__(Consume, false)
struct ActorBase
{
uint32_t value;
bool unknown1;
bool unknown2;
};
__ParserAttribute__(Consume, false)
struct PartyLeader
{
OnlineID id;
};
__ParserAttribute__(Consume, false)
struct ProductAttributeUserColorSingle : public ProductAttribute
{
bool hasValue;
uint32_t value;
};
__ParserAttribute__(Consume, false)
struct ProductAttributeUserColorRGB : public ProductAttribute
{
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
__ParserAttribute__(Consume, false)
struct ProductAttributeTitle : public ProductAttribute
{
std::string title;
};
__ParserAttribute__(Consume, false)
struct ProductAttributeSingleValue : public ProductAttribute
{
uint32_t value;
};
__ParserAttribute__(Consume, false)
struct ProductAttributePainted : public ProductAttributeSingleValue
{
};
__ParserAttribute__(Consume, false)
struct ProductAttributeTeamEdition : public ProductAttributeSingleValue
{
};
__ParserAttribute__(Consume, false)
struct ProductAttributeSpecialEdition : public ProductAttributeSingleValue
{
};
using AttributeType = std::variant<ProductAttributeUserColorRGB, ProductAttributeUserColorSingle,
ProductAttributePainted, ProductAttributeTeamEdition, ProductAttributeTitle,
ProductAttributeSpecialEdition, ProductAttribute>;
struct Attributes
{
//uint8_t attributes_count; //Is automatically read when consuming vector
__ParserAttribute__(CallConsume, true)
std::vector<AttributeType> product_attributes;
};
struct OnlineLoadout
{
//uint8_t attributes_list_count;//Is automatically read when consuming vector
__ParserAttribute__(CallToString, true)
__ParserAttribute__(CallConsume, true)
std::vector<Attributes> attributes_list;
};
struct ClientLoadoutsOnline
{
__ParserAttribute__(CallConsume, true)
OnlineLoadout online_one;
__ParserAttribute__(CallConsume, true)
OnlineLoadout online_two;
bool loadout_set;
bool is_deprecated;
};
struct ClientLoadouts
{
__ParserAttribute__(CallConsume, true)
ClientLoadout loadout_one;
__ParserAttribute__(CallConsume, true)
ClientLoadout loadout_two;
};
struct ClubColors
{
bool team_color_set;
uint8_t team_color_id;
bool custom_color_set;
uint8_t custom_color_id;
};
struct WeldedInfo
{
bool active;
int32_t actor_id;
Vector3 offset;
float mass;
Rotator rotation;
};
struct ReplicatedBoostData
{
uint8_t grant_count;
uint8_t boost_amount;
uint8_t unused1;
uint8_t unused2;
};
enum EBreakoutDamageState
{
DamageState_Start,
DamageState_Damaged,
DamageState_Broken,
DamageState_MAX
};
struct DamageState
{
uint8_t damage_state;
bool unknown2;
int32_t causer_actor_id;
Vector3 damage_location;
bool direct_damage;
bool immediate;
};
struct AppliedDamage
{
uint8_t id;
Vector3 position;
int32_t damage_index;
int32_t total_damage;
};
struct ReplicatedExplosionData
{
bool unknown1;
uint32_t actor_id;
Vector3 position;
};
struct ReplicatedExplosionDataExtended
{
bool unknown1;
int32_t actor_id;
Vector3 position;
bool unknown3;
int32_t secondary_actor_id;
};
struct ReplicatedTitle
{
bool unknown1;
bool unknown2;
uint32_t unknown3;
uint32_t unknown4;
uint32_t unknown5;
uint32_t unknown6;
uint32_t unknown7;
bool unknown8;
};
struct ImpulseData
{
int CompressedRotation;
float ImpulseSpeed;
};
struct HistoryKey
{
__ParserAttribute__(NumBits, 14)
uint16_t data;
};
struct ReplicatedStatEvent
{
bool unknown1;
int32_t object_id;
};
struct RepStatTitle
{
bool unknown1;
std::string name;
__ParserAttribute__(CallConsume, true)
ObjectTarget object_target;
uint32_t value;
};
struct SkillTier
{
__ParserAttribute__(MaxBits, 500)
uint32_t tier;
};
//Probably not relevant for most, is only used for KActors in workshop replays
//__ParserAttribute__(Consume, false)
struct RigidBodyState
{
Vector3 position;
Vector3 lin_vel;
Quat quaternion;
Vector3 ang_vel;
uint32_t flags;
};
__ParserAttribute__(Consume, false)
struct PickupInfo_TA
{
ActiveActor AvailablePickups;
//Not entirely sure what this is yet
bool unknown;
bool bItemsArePreview;
};
}
#include "GameClasses.h"
| 8,863
|
C++
|
.h
| 385
| 20.25974
| 136
| 0.757677
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,029
|
ReplayFileData.h
|
Bakkes_CPPRP/CPPRP/data/ReplayFileData.h
|
#pragma once
#include <stdint.h>
#include <any>
#include <string>
#include <vector>
#include <unordered_map>
#include <iostream>
#include <memory>
#include <variant>
/*
This file contains all base types such as vectors and rotators (mostly classes that are read in the bitreader directly)
It also contains data structures for things that are stored in the header of a replay
*/
namespace CPPRP
{
struct Vector3
{
float x{ 0 };
float y{ 0 };
float z{ 0 };
std::string ToString() const
{
return std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z);
}
};
struct Vector3I
{
int x{ 0 };
int y{ 0 };
int z{ 0 };
explicit operator Vector3() const
{
return Vector3
{
static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)
};
};
std::string ToString() const
{
return std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z);
}
};
struct Rotator
{
int pitch{ 0 };
int yaw{ 0 };
int roll{ 0 };
std::string ToString() const
{
return std::to_string(pitch) + ", " + std::to_string(yaw) + ", " + std::to_string(roll);
}
};
struct Quat
{
float x{ 0 };
float y{ 0 };
float z{ 0 };
float w{ 0 };
std::string ToString() const
{
return std::to_string(w) + ", " + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z);
}
};
enum Platform
{
Platform_Unknown = 0,
Platform_Steam = 1,
Platform_PS4 = 2,
Platform_PS3 = 3,
Platform_Dingo = 4,
Platform_QQ = 5,
Platform_Switch = 6, //Is in gamefiles as wegame..
//Platform_NNX = 7,
Platform_PsyNet = 7, //is 8 in gamefiles
Platform_Epic = 11,
Platform_MAX = 12
};
struct UniqueId
{
uint8_t platform{ 0 };
uint8_t splitscreenID{ 0 };
//uint64_t uniqueID{ 0 };
std::string ToString() const
{
return "";// return std::to_string(platform) + "|" + std::to_string(uniqueID) + "|" + std::to_string(playerNumber);
}
virtual ~UniqueId() {}
};
struct SteamID : public UniqueId
{
uint64_t steamID{ 0 };
};
struct XBoxID : public UniqueId
{
uint64_t xboxID{ 0 };
};
struct QQID : public UniqueId
{
uint64_t qqID{ 0 };
};
struct SwitchID : public UniqueId
{
uint64_t a{ 0 };
uint64_t b{ 0 };
uint64_t c{ 0 };
uint64_t d{ 0 };
};
struct PS4ID : public UniqueId
{
std::string playerName;
uint64_t unknown1{ 0 };
uint64_t unknown2{ 0 };
uint64_t psId{ 0 };
};
struct PsyNetID : public UniqueId
{
uint64_t a{ 0 };
uint64_t b{ 0 };
uint64_t c{ 0 };
uint64_t d{ 0 };
};
struct EpicID : public UniqueId
{
std::string epicId;
};
struct UnknownId : public UniqueId
{
uint32_t unknown{ 0 };
};
using OnlineID = std::variant<UniqueId, SteamID, XBoxID, SwitchID, QQID, PS4ID, PsyNetID, EpicID, UnknownId>;
struct EnumProperty
{
std::string type;
std::variant<std::string, uint8_t> value;
};
struct Property;
struct StructProperty
{
std::string name;
std::vector<std::shared_ptr<Property>> fields;
};
using PropertyObj = std::unordered_map<std::string, std::shared_ptr<Property>>;
using PropertyValue = std::variant<std::string, int32_t, uint32_t, uint8_t, uint64_t, float, EnumProperty, std::vector<PropertyObj>, StructProperty>;
struct Property
{
std::string property_name;
std::string property_type;
PropertyValue value;
};
struct FileHeader
{
uint32_t size{ 0 };
uint32_t crc{ 0 };
uint32_t engineVersion{ 0 };
uint32_t licenseeVersion{ 0 };
uint32_t netVersion{ 0 };
std::string buildVersion{ "" };
};
struct KeyFrame
{
float time{ 0.f };
uint32_t frame{ 0 };
uint32_t filepos{ 0 };
};
struct ReplayTick
{
std::string type;
uint32_t frame{ 0 };
};
struct ClassIndex
{
std::string class_name;
uint32_t index{ 0 };
};
struct PropIndexId
{
int32_t prop_index{ 0 };
int32_t prop_id{ 0 };
};
struct ClassNet
{
int32_t index{ 0 };
int32_t parent{ 0 };
std::shared_ptr<ClassNet> parent_class{ nullptr };
int32_t id{ 0 };
int32_t prop_indexes_size{ 0 };
std::vector<PropIndexId> prop_indexes;
uint16_t max_prop_id{ 0 };
std::vector<uint16_t> property_id_cache;
};
struct ActorState
{
std::shared_ptr<ClassNet> classNet{ nullptr };
uint32_t actor_id{ 0 };
uint32_t name_id{ 0 };
bool alive{ false };
std::unordered_map<std::string, std::shared_ptr<void>> fields;
//Vector3 position;
//Rotator rotation;
};
struct Frame
{
uint32_t frameNumber;
float time;
float delta;
size_t position;
//std::unordered_map<uint32_t, ActorState> states;
};
struct DebugString
{
uint32_t frame;
std::string key;
std::string value;
};
struct ReplayFileData
{
//All header props
FileHeader header;
std::string replayType;
std::unordered_map<std::string, std::shared_ptr<Property>> properties;
uint32_t body_size;
uint32_t crc2;
std::vector<std::string> levels;
std::vector<KeyFrame> keyframes;
uint32_t netstream_size;
const char* netstream_data;
std::vector<DebugString> debugstrings;
std::vector<ReplayTick> replayticks;
std::vector<std::string> replicated_packages;
std::vector<std::string> objects;
std::vector<std::string> names;
std::vector<ClassIndex> class_indices;
std::vector<std::shared_ptr<ClassNet>> classnets;
};
}
| 5,281
|
C++
|
.h
| 237
| 19.531646
| 150
| 0.669466
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,030
|
ArcheTypes.h
|
Bakkes_CPPRP/CPPRP/data/ArcheTypes.h
|
#pragma once
#include <vector>
#include <string>
namespace CPPRP
{
static const std::vector<std::pair<std::string, std::vector<std::string>>> archetypeMap =
{
{{"TAGame.Car_TA"}, {"Archetypes.Car.Car_Default", "TAGame.Default__Car_TA"}},
{{"TAGame.Car_TA"}, {"Mutators.Mutators.Mutators.FreePlay:CarArchetype"}},
{{"TAGame.Ball_TA"}, { "Archetypes.Ball.Ball_Football", "Archetypes.Ball.Ball_Training"}},
{{"TAGame.Ball_TA"}, {"Archetypes.Ball.Ball_GameEditor", "Archetypes.Ball.Ball_Default", "Archetypes.Ball.Ball_Basketball", "Archetypes.Ball.Ball_BasketBall", "Archetypes.Ball.Ball_BasketBall_Mutator", "Archetypes.Ball.Ball_Puck", "Archetypes.Ball.CubeBall", "Archetypes.Ball.Ball_Beachball", "Archetypes.Ball.Ball_Anniversary"}},
{{"TAGame.Ball_Breakout_TA"}, {"Archetypes.Ball.Ball_Breakout"}},
{{"TAGame.Ball_God_TA"}, {"Archetypes.Ball.Ball_God"}},
{{"TAGame.Ball_TA"},{"Archetypes.Ball.Ball_Trajectory"}},
{{"TAGame.CarComponent_Boost_TA"}, {"Archetypes.CarComponents.CarComponent_Boost"}},
{{"TAGame.CarComponent_Dodge_TA"}, {"Archetypes.CarComponents.CarComponent_Dodge"}},
{{"TAGame.CarComponent_DoubleJump_TA"}, {"Archetypes.CarComponents.CarComponent_DoubleJump"}},
{{"TAGame.CarComponent_FlipCar_TA"}, {"Archetypes.CarComponents.CarComponent_FlipCar"}},
{{"TAGame.CarComponent_Jump_TA"}, {"Archetypes.CarComponents.CarComponent_Jump"}},
{{"TAGame.Team_Soccar_TA"}, {"Archetypes.Teams.Team0", "Archetypes.Teams.Team1"}},
{{"TAGame.PRI_TA"}, {"TAGame.Default__PRI_TA", "TAGame.Default__PRI_Breakout_TA"}},
{{"TAGame.GameEvent_TrainingEditor_TA"}, {"Archetypes.GameEvent.GameEvent_TrainingEditor"}},
{{"TAGame.GameEvent_Tutorial_TA"}, {"GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Aerial", "GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Goalie", "GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Striker_TA", "GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Striker"}},
//{{"TAGame.GameEvent_Tutorial_Goalie_TA"}, {"GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Goalie"}},
//{{"TAGame.GameEvent_Tutorial_Striker_TA"}, {"GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Striker_TA"}},
{{"TAGame.GameEvent_Soccar_TA"}, {/*"GameInfo_Tutorial.GameEvent.GameEvent_Tutorial_Aerial",*/ "Archetypes.GameEvent.GameEvent_Basketball", "Archetypes.GameEvent.GameEvent_Hockey", "Archetypes.GameEvent.GameEvent_Soccar", "Archetypes.GameEvent.GameEvent_Items", "Archetypes.GameEvent.GameEvent_SoccarLan", "Archetypes.GameEvent.GameEvent_FTE_Part1_Prime", "GameInfo_Basketball.GameInfo.GameInfo_Basketball:Archetype"}},
{{"TAGame.GameEvent_SoccarPrivate_TA"}, {"Archetypes.GameEvent.GameEvent_SoccarPrivate", "Archetypes.GameEvent.GameEvent_BasketballPrivate", "Archetypes.GameEvent.GameEvent_HockeyPrivate"}},
{{"TAGame.GameEvent_SoccarSplitscreen_TA"}, {"Archetypes.GameEvent.GameEvent_SoccarSplitscreen", "Archetypes.GameEvent.GameEvent_BasketballSplitscreen", "Archetypes.GameEvent.GameEvent_HockeySplitscreen"}},
{{"TAGame.GameEvent_Season_TA"}, {"Archetypes.GameEvent.GameEvent_Season"}},
{{"TAGame.Car_TA"}, {"Archetypes.GameEvent.GameEvent_Season:CarArchetype", "Archetypes.Car.Car_PostGameLobby"}},
{{"TAGame.GameEvent_Breakout_TA"}, {"Archetypes.GameEvent.GameEvent_Breakout"}},
{{"TAGame.GameEvent_GodBall_TA"}, {"gameinfo_godball.GameInfo.gameinfo_godball:Archetype", "GameInfo_GodBall.GameInfo.GameInfo_GodBall:Archetype"}},
{{"TAGame.GameEvent_Football_TA"}, {"GameInfo_FootBall.GameInfo.GameInfo_FootBall:Archetype"}},
{{"TAGame.GRI_TA"}, {"GameInfo_KnockOut.KnockOut.GameInfo_KnockOut:GameReplicationInfoArchetype", "GameInfo_TrainingEditor.GameInfo.GameInfo_TrainingEditor:GameReplicationInfoArchetype", "GameInfo_Tutorial.GameInfo.GameInfo_Tutorial:GameReplicationInfoArchetype", "GameInfo_Basketball.GameInfo.GameInfo_Basketball:GameReplicationInfoArchetype", "Gameinfo_Hockey.GameInfo.Gameinfo_Hockey:GameReplicationInfoArchetype", "GameInfo_Season.GameInfo.GameInfo_Season:GameReplicationInfoArchetype", "GameInfo_Soccar.GameInfo.GameInfo_Soccar:GameReplicationInfoArchetype", "GameInfo_Items.GameInfo.GameInfo_Items:GameReplicationInfoArchetype", "GameInfo_Breakout.GameInfo.GameInfo_Breakout:GameReplicationInfoArchetype", "gameinfo_godball.GameInfo.gameinfo_godball:GameReplicationInfoArchetype", "GameInfo_GodBall.GameInfo.GameInfo_GodBall:GameReplicationInfoArchetype", "GameInfo_FootBall.GameInfo.GameInfo_FootBall:GameReplicationInfoArchetype", "GameInfo_FTE.GameInfo.GameInfo_FTE:GameReplicationInfoArchetype"}},
{{"TAGame.CameraSettingsActor_TA"}, {"TAGame.Default__CameraSettingsActor_TA"}},
{{"TAGame.InMapScoreboard_TA"}, {"Neotokyo_p.TheWorld:PersistentLevel.InMapScoreboard_TA_0", "NeoTokyo_P.TheWorld:PersistentLevel.InMapScoreboard_TA_0", "NeoTokyo_P.TheWorld:PersistentLevel.InMapScoreboard_TA_1", "NeoTokyo_Standard_P.TheWorld:PersistentLevel.InMapScoreboard_TA_1", "NeoTokyo_Standard_P.TheWorld:PersistentLevel.InMapScoreboard_TA_0", "Neotokyo_p.TheWorld:PersistentLevel.InMapScoreboard_TA_1", "NeoTokyo_Toon_p.TheWorld:PersistentLevel.InMapScoreboard_TA_0", "NeoTokyo_Toon_p.TheWorld:PersistentLevel.InMapScoreboard_TA_1"}},
{{"TAGame.SpecialPickup_BallGravity_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_GravityWell", "Archetypes.SpecialPickups.BM.SpecialPickup_GravityWell_BM"}},
{{"TAGame.SpecialPickup_BallVelcro_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_BallVelcro", "Archetypes.SpecialPickups.BM.SpecialPickup_BallVelcro_BM"}},
{{"TAGame.SpecialPickup_BallLasso_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_BallLasso", "Archetypes.SpecialPickups.BM.SpecialPickup_BallLasso_BM"}},
{{"TAGame.SpecialPickup_GrapplingHook_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_BallGrapplingHook", "Archetypes.SpecialPickups.BM.SpecialPickup_BallGrapplingHook_BM"}},
{{"TAGame.SpecialPickup_Swapper_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_Swapper", "Archetypes.SpecialPickups.BM.SpecialPickup_Swapper_BM"}},
{{"TAGame.SpecialPickup_BallFreeze_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_BallFreeze", "Archetypes.SpecialPickups.BM.SpecialPickup_BallFreeze_BM"}},
{{"TAGame.SpecialPickup_BoostOverride_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_BoostOverride", "Archetypes.SpecialPickups.BM.SpecialPickup_BoostOverride_BM"}},
{{"TAGame.SpecialPickup_Tornado_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_Tornado", "Archetypes.SpecialPickups.BM.SpecialPickup_Tornado_BM"}},
{{"TAGame.SpecialPickup_BallCarSpring_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_CarSpring", "Archetypes.SpecialPickups.SpecialPickup_BallSpring", "Archetypes.SpecialPickups.BM.SpecialPickup_CarSpring_BM", "Archetypes.SpecialPickups.BM.SpecialPickup_BallSpring_BM"}},
{{"TAGame.SpecialPickup_HitForce_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_StrongHit", "Archetypes.SpecialPickups.BM.SpecialPickup_StrongHit_BM"}},
{{"TAGame.SpecialPickup_Batarang_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_Batarang"}},
{{"TAGame.SpecialPickup_Football_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_Football"}},
//{{"TAGame.SpecialPickup_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_Swapper"}},
//{{"TAGame.SpecialPickup_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_GravityWell"}},
//{{"TAGame.InMapScoreboard_TA"}, {"Neotokyo_p.TheWorld:PersistentLevel.InMapScoreboard_TA_1"}},
{{"TAGame.Ball_Haunted_TA"}, {"Archetypes.Ball.Ball_Haunted"}},
{{"TAGame.HauntedBallTrapTrigger_TA"}, {"Haunted_TrainStation_P.TheWorld:PersistentLevel.HauntedBallTrapTrigger_TA_1", "Haunted_TrainStation_P.TheWorld:PersistentLevel.HauntedBallTrapTrigger_TA_0"}},
{{"TAGame.SpecialPickup_HauntedBallBeam_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_HauntedBallBeam"}},
{{"TAGame.SpecialPickup_Rugby_TA"}, {"Archetypes.SpecialPickups.SpecialPickup_Rugby"}},
{{"TAGame.Cannon_TA"}, {"Archetypes.Tutorial.Cannon"}},
{{"TAGame.GameEditor_Pawn_TA"}, {"Archetypes.GameEditor.GameEditor_Pawn_Default"} },
{{"ProjectX.NetModeReplicator_X"}, {"ProjectX.Default__NetModeReplicator_X"}},
{{"TAGame.MaxTimeWarningData_TA" }, {"TAGame.Default__MaxTimeWarningData_TA"}}, //TAGame.Default__MaxTimeWarningData_TA
{{"TAGame.RumblePickups_TA" }, {"TAGame.Default__RumblePickups_TA"}},
{{"TAGame.PickupTimer_TA"}, {"TAGame.Default__PickupTimer_TA"}},
{{"TAGame.PRI_KnockOut_TA"}, {"TAGame.Default__PRI_KnockOut_TA"}},
{{"TAGame.GameEvent_KnockOut_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout"}},
{{"TAGame.Car_KnockOut_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype"}},
{{"TAGame.CarComponent_DoubleJump_KO_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.Jump"}},
{{"TAGame.CarComponent_Torque_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.Torque"}},
{{"TAGame.CarComponent_FlipCar_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.Flip"}},
{{"TAGame.CarComponent_Dodge_KO_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.Dodge"}},
{{"TAGame.CarComponent_DoubleJump_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.DoubleJump"}},
{{"TAGame.CarComponent_Boost_KO_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.Boost"}},
{{"TAGame.Stunlock_TA"}, {"Archetypes.KnockOut.GameEvent_Knockout:CarArchetype.StunlockArchetype"}}
};
}
| 9,248
|
C++
|
.h
| 73
| 123.90411
| 1,009
| 0.786944
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,031
|
ParseException.h
|
Bakkes_CPPRP/CPPRP/exceptions/ParseException.h
|
#pragma once
#include <exception>
#include <string>
#include <sstream>
#include "../CPPBitReader.h"
namespace CPPRP
{
template<typename T>
struct ParseException : public std::exception
{
protected:
const CPPBitReader<T>& bitReader;
explicit ParseException(const CPPBitReader<T>& br);
public:
std::string errorMsg;
const char* what() const throw();
};
template<typename T>
struct GeneralParseException : public ParseException<T>
{
protected:
std::string message;
public:
explicit GeneralParseException(const std::string& message, const CPPBitReader<T>& br);
};
struct PropertyDoesNotExistException : public std::exception
{
protected:
std::string propertyName;
std::string errorMsg;
public:
explicit PropertyDoesNotExistException(const std::string& propertyName_);
virtual ~PropertyDoesNotExistException();
const char* what() const throw();
};
template<typename T>
struct AttributeParseException : public ParseException<T>
{
protected:
std::string failedAttribute;
public:
AttributeParseException(const std::string& attribute, const CPPBitReader<T>& br);
};
template<typename T>
inline ParseException<T>::ParseException(const CPPBitReader<T>& br) : bitReader(br)
{
std::stringstream ss;
auto absPos = (bitReader.t_position * sizeof(T) * 8) + bitReader.bit_position;
ss << "T_POS=" << std::to_string(bitReader.t_position) << ", BIT_POS=" << std::to_string(bitReader.bit_position) << ", ABS=" << absPos << "/" << bitReader.size;
ss << ". Version(" << std::to_string(bitReader.engineVersion) << ", " << std::to_string(bitReader.licenseeVersion) << ", " << std::to_string(bitReader.netVersion) << ")";
errorMsg = ss.str();
}
template<typename T>
const char* ParseException<T>::what() const throw()
{
return errorMsg.c_str();
}
template<typename T>
inline AttributeParseException<T>::AttributeParseException(const std::string& attribute, const CPPBitReader<T>& br) : ParseException<T>(br), failedAttribute(attribute)
{
std::stringstream ss;
ss << "Failed to parse attribute \"" << failedAttribute << "\". ";
this->errorMsg = ss.str() + this->errorMsg;
}
template<typename T>
inline GeneralParseException<T>::GeneralParseException(const std::string& message_, const CPPBitReader<T>& br) : ParseException<T>(br), message(message_)
{
this->errorMsg = message + " " + this->errorMsg;
}
}
| 2,372
|
C++
|
.h
| 70
| 31.542857
| 172
| 0.733973
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,032
|
ReplayException.h
|
Bakkes_CPPRP/CPPRP/exceptions/ReplayException.h
|
#pragma once
#include <exception>
#include <stdint.h>
#include <string>
namespace CPPRP
{
struct InvalidVersionException : public std::exception
{
protected:
uint32_t engineVersion;
uint32_t licenseeVersion;
uint32_t netVersion;
std::string errorMsg;
public:
InvalidVersionException(const uint32_t engine, const uint32_t licensee, const uint32_t net);
virtual ~InvalidVersionException();
const char* what() const throw();
};
}
| 447
|
C++
|
.h
| 19
| 21.473684
| 94
| 0.782201
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,033
|
CPPBM.h
|
Bakkes_CPPRP/CPPRPBM/CPPBM.h
|
#pragma once
#undef byte
#include "bakkesmod/plugin/bakkesmodplugin.h"
#pragma comment( lib, "bakkesmod.lib" )
#pragma comment(lib, "CPPRP.lib")
#include "../CPPRP/ReplayFile.h"
#include "../CPPRP/exceptions/ReplayException.h"
struct ReplicationData
{
CPPRP::ReplicatedRBState rbState;
int steer;
bool handbrake;
int throttle;
float delta;
};
class CPPBM : public BakkesMod::Plugin::BakkesModPlugin
{
private:
uint32_t currentFrameIngame = 0;
uint32_t currentFrame = 0;
std::chrono::time_point<std::chrono::system_clock> timeApplied;
std::shared_ptr<CPPRP::ReplayFile> replayFile;
std::map<uint32_t, std::map<uint32_t, ReplicationData>> locations;
public:
virtual void onLoad();
virtual void onUnload();
void GVCTick(std::string name);
void OnTick(CarWrapper cw, void * params, std::string funcName);
};
| 822
|
C++
|
.h
| 29
| 26.724138
| 67
| 0.775665
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,034
|
IReplayPlayer.h
|
Bakkes_CPPRP/CPPRPPlayer/IReplayPlayer.h
|
#pragma once
#include <memory>
#pragma comment(lib, "CPPRP.lib")
#include "../CPPRP/ReplayFile.h"
#include <set>
namespace CPPRP
{
namespace ReplayPlaying
{
using namespace CPPRP;
typedef std::function<void(const std::shared_ptr<Engine::Actor>& actor, std::string& propertyName)> ValueUpdate;
#define FIELD(f) Field(&f, #f ).ToString()
enum class GameState : uint8_t
{
Countdown = 0b1,
PlayingNormal = 0b01,
PlayingOT = 0b001,
PostGoal = 0b0001,
PostGame = 0b00001,
Playing = PlayingNormal | PlayingOT
};
template<typename T>
struct Field
{
protected:
std::string name_;
public:
Field(T a, std::string name)
{
name[name.find(':')] = '.';
name = name.erase(name.find(':'), 1);
name = name.erase(name.find(':'), 1);
name_ = name;
//printf("#######%s\n", typeid(T).name());
//printf("$$$$$$$$%s\n", name.c_str());
//auto b = &a;
}
std::string ToString()
{
return name_;
}
//auto a = &ProjectX::GRI_X::bGameStarted;
};
class IReplayPlayer
{
private:
std::shared_ptr<ReplayFile> replay_;
std::unordered_map<uint32_t, std::vector<ValueUpdate>> variableUpdates_;
GameState currentGameState_ = GameState::Countdown;
float timeSinceBallHit = 0.f;
bool lastVal = true;
std::set<float> kickoffSpeeds;
std::set<float> scoreSpeeds;
public:
float GetFastestKickoff();
float GetFastestGoal();
float GetSlowestGoal();
IReplayPlayer(std::shared_ptr<CPPRP::ReplayFile> replay);
void OnTick(const Frame frame, const std::unordered_map<int, ActorStateData>& actorData);
void OnNewFrame(const Frame frame);
void OnActorCreated(const ActorStateData& createdActor);
void OnActorUpdated(const ActorStateData& updatedActor, const std::vector<uint32_t>& updatedProperties);
void OnActorDeleted(const ActorStateData& deletedActor);
template<typename T2, typename T>
void RegisterActorUpdate(std::string variable, T callback)
{
const uint32_t replicatedIndex = replay_->objectToId[variable];
//printf("%s@@\n", typeid(T2).name());
variableUpdates_[replicatedIndex].push_back([callback, &variable](const std::shared_ptr<Engine::Actor>& actor, std::string& propertyName)
{
callback(std::dynamic_pointer_cast<T2>(actor), variable);// , static_cast<T3*>(newValue));
});
};
template<typename T>
std::shared_ptr<T> GetActiveActor(ActiveActor& aa)
{
return std::dynamic_pointer_cast<T>(replay_->actorStates[aa.actor_id]);
}
template<typename T>
std::shared_ptr<T> GetActiveActor(ObjectTarget& aa)
{
return std::dynamic_pointer_cast<T>(replay_->actorStates[aa.object_index]);
}
};
}
}
| 2,701
|
C++
|
.h
| 86
| 27.546512
| 141
| 0.689376
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,051
|
xframe_utils.hpp
|
Bakkes_CPPRP/CPPRPPlayer/include/xframe/xframe_utils.hpp
|
/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XFRAME_XFRAME_UTILS_HPP
#define XFRAME_XFRAME_UTILS_HPP
#include <iterator>
#include <ostream>
#include <string>
#include "xtensor/xio.hpp"
#include "xframe_config.hpp"
#include "xframe_trace.hpp"
namespace xf
{
constexpr std::size_t dynamic()
{
return std::numeric_limits<std::size_t>::max();
}
template <class CO, class... CI>
bool merge_to(CO& output, const CI&... input);
template <class CO, class... CI>
bool intersect_to(CO& output, const CI&... input);
/***************************
* merge_to implementation *
***************************/
namespace detail
{
template <class C0, class C1>
inline bool merge_containers(C0& output, const C1& input)
{
bool res = !(input.size() < output.size());
auto output_iter = output.begin();
auto output_end = output.end();
auto first = input.begin();
auto last = input.end();
while(first != last && output_iter != output_end)
{
if(*first < *output_iter)
{
output_iter = output.insert(output_iter, *first++);
output_end = output.end();
res = false;
}
else if(*first == *output_iter)
{
++first;
}
++output_iter;
}
res &= output.empty() || (first == last);
std::copy(first, last, std::back_inserter(output));
return res;
}
template <class C0>
inline bool merge_to_impl(C0&)
{
return true;
}
template <class C0, class C1, class... C>
inline bool merge_to_impl(C0& out, C1& in, const C&... input)
{
bool res = merge_containers(out, in);
res &= merge_to_impl(out, input...);
return res;
}
template <class S, std::size_t N>
struct xselector_sequence
{
using type = std::conditional_t<N == std::numeric_limits<std::size_t>::max(), std::vector<S>, std::array<S, N>>;
};
template <class S, std::size_t N>
using xselector_sequence_t = typename xselector_sequence<S, N>::type;
}
template <class CO, class... CI>
inline bool merge_to(CO& output, const CI&... input)
{
return detail::merge_to_impl(output, input...);
}
/*******************************
* intersect_to implementation *
*******************************/
namespace detail
{
template <class C0, class C1>
inline bool intersect_containers(C0& output, const C1& input)
{
bool res = !(input.size() < output.size());
auto output_iter = output.begin();
auto output_end = output.end();
auto first = input.begin();
auto last = input.end();
while(first != last && output_iter != output_end)
{
if(*first < *output_iter)
{
++first;
}
else if(*first == *output_iter)
{
++first;
++output_iter;
}
else // *first > *output_iter
{
output_iter = output.erase(output_iter);
output_end = output.end();
res = false;
}
}
res &= (output_iter == output_end);
output.erase(output_iter, output_end);
return res;
}
template <class C0>
inline bool intersect_to_impl(C0&)
{
return true;
}
template <class C0, class C1, class... C>
inline bool intersect_to_impl(C0& out, const C1& in, const C&... input)
{
bool res = intersect_containers(out, in);
res &= intersect_to_impl(out, input...);
return res;
}
}
template <class CO, class... CI>
inline bool intersect_to(CO& output, const CI&... input)
{
return detail::intersect_to_impl(output, input...);
}
/******************
* print function *
******************/
template <class V>
inline std::ostream& print_variable_expression(std::ostream& out, const V& v)
{
const auto& dims = v.dimension_labels();
const auto& coords = v.coordinates();
out << v.data() << std::endl;
out << "Coordinates:" << std::endl;
std::size_t max_length = std::accumulate(dims.cbegin(), dims.cend(), std::size_t(0),
[](std::size_t res, const auto& d) { return std::max(res, d.size()); });
for (const auto& d : dims)
{
std::size_t nb_spaces = max_length - d.size();
std::string spaces(nb_spaces, ' ');
out << d << spaces << ": " << coords[d] << std::endl;
}
return out;
}
}
#endif
| 5,747
|
C++
|
.h
| 158
| 26.639241
| 124
| 0.457127
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,533,052
|
xaxis_scalar.hpp
|
Bakkes_CPPRP/CPPRPPlayer/include/xframe/xaxis_scalar.hpp
|
/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XFRAME_XAXIS_SCALAR_HPP
#define XFRAME_XAXIS_SCALAR_HPP
#include "xtl/xvariant.hpp"
#include "xtl/xmeta_utils.hpp"
#include "xtensor/xoptional.hpp"
#include "xframe_config.hpp"
#include "xframe_utils.hpp"
#include "xframe_expression.hpp"
namespace xf
{
struct xaxis_scalar_name
{
};
/****************
* xaxis_scalar *
****************/
template <class CT>
class xaxis_scalar
{
public:
using name_type = xaxis_scalar_name;
using data_type = xt::xscalar<CT>;
using value_type = typename data_type::value_type;
using reference = typename data_type::reference;
using const_reference = typename data_type::const_reference;
using pointer = typename data_type::pointer;
using const_pointer = typename data_type::const_pointer;
using size_type = typename data_type::size_type;
using expression_tag = xaxis_expression_tag;
xaxis_scalar(const xt::xscalar<CT>& v) noexcept;
template <std::size_t N = dynamic(), class S>
const_reference operator()(S&& /*selector*/) const;
private:
data_type m_data;
};
/*******************************
* xaxis_scalar implementation *
*******************************/
template <class CT>
xaxis_scalar<CT>::xaxis_scalar(const xt::xscalar<CT>& v) noexcept
: m_data(v)
{
}
template <class CT>
template <std::size_t N, class S>
auto xaxis_scalar<CT>::operator()(S&& /*selector*/) const -> const_reference
{
return m_data;
}
}
#endif
| 2,290
|
C++
|
.h
| 60
| 33.2
| 80
| 0.504069
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,533,077
|
xaxis_meta.hpp
|
Bakkes_CPPRP/CPPRPPlayer/include/xframe/xaxis_meta.hpp
|
/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XFRAME_XAXIS_META_HPP
#define XFRAME_XAXIS_META_HPP
#include "xtl/xbasic_fixed_string.hpp"
#include "xtl/xvariant.hpp"
#include "xtl/xmeta_utils.hpp"
#include "xframe_config.hpp"
#include "xaxis_scalar.hpp"
namespace xf
{
template <class K, class T, class MT, class L, class LT>
class xnamed_axis;
template <class CTA>
class xaxis_expression_leaf;
namespace detail
{
template <class... Args>
struct common_name_type;
template <class T, class... Args>
struct common_name_type<T, Args...>
{
using tmp_type = typename common_name_type<Args...>::type;
using type = typename common_name_type<T, tmp_type>::type;
};
template <class T1, class T2>
struct common_name_type<T1, xaxis_scalar<T2>>
{
using type = typename T1::name_type;
};
template <class T1, class T2>
struct common_name_type<xaxis_scalar<T1>, T2>
{
using type = typename T2::name_type;
};
template <class T1, class T2>
struct common_name_type<xaxis_scalar<T1>, xaxis_scalar<T2>>
{
using type = xaxis_scalar_name;
};
template <class T1, class T2>
struct common_name_type<T1, T2>
{
using type = std::common_type_t<typename T1::name_type, typename T2::name_type>;
};
template <class... Args>
using common_name_type_t = typename common_name_type<Args...>::type;
template <class CTA, bool val>
struct axis_closure_getter
{
static auto get_axis_closure(CTA&& axis)
{
return xaxis_expression_leaf<CTA>(std::forward<CTA>(axis));
}
};
template <class CTA>
struct axis_closure_getter<CTA, false>
{
static auto get_axis_closure(CTA&& axis)
{
return std::forward<CTA>(axis);
}
};
template <class T>
struct is_named_axis : std::false_type
{
};
template <class K, class T, class MT, class L, class LT>
struct is_named_axis<xnamed_axis<K, T, MT, L, LT>> : std::true_type
{
};
template <class CTA>
auto get_axis_closure(CTA&& axis)
{
return axis_closure_getter<CTA, is_named_axis<std::decay_t<CTA>>::value>::get_axis_closure(std::forward<CTA>(axis));
}
}
/*****************
* xaxis_closure *
*****************/
template <class CT>
struct xaxis_closure
{
using type = CT;
};
template <class CT>
using xaxis_closure_t = typename xaxis_closure<CT>::type;
/****************************
* xaxis_expression_closure *
****************************/
template <class CT, bool val>
struct axis_expression_closure_getter
{
using type = xaxis_expression_leaf<CT>;
};
template <class CT>
struct axis_expression_closure_getter<CT, false>
{
using type = CT;
};
template <class CT>
struct axis_expression_closure_getter<xt::xscalar<CT>, false>
{
using type = xaxis_scalar<CT>;
};
template <class CT>
struct xaxis_expression_closure
{
using type = typename axis_expression_closure_getter<CT, detail::is_named_axis<std::decay_t<CT>>::value>::type;
};
template <class CT>
using xaxis_expression_closure_t = typename xaxis_expression_closure<CT>::type;
}
#endif
| 4,244
|
C++
|
.h
| 121
| 27.793388
| 128
| 0.521856
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| true
| false
| true
| false
|
1,533,145
|
GeneratedSerializeFunctions.h
|
Bakkes_CPPRP/CPPRPJSON/GeneratedSerializeFunctions.h
|
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedRBState& item)
{
writer.StartObject();
writer.Key("rotation");
Serialize(writer, item.rotation);
writer.Key("position");
Serialize(writer, item.position);
writer.Key("linear_velocity");
Serialize(writer, item.linear_velocity);
writer.Key("angular_velocity");
Serialize(writer, item.angular_velocity);
writer.Key("sleeping");
Serialize(writer, item.sleeping);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const GameServer& item)
{
writer.StartObject();
writer.Key("GameServerID");
Serialize(writer, item.GameServerID);
writer.Key("GameServerIDString");
Serialize(writer, item.GameServerIDString);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const LogoData& item)
{
writer.StartObject();
writer.Key("swap_colors");
Serialize(writer, item.swap_colors);
writer.Key("logo_id");
Serialize(writer, item.logo_id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ActiveActor& item)
{
writer.StartObject();
writer.Key("active");
Serialize(writer, item.active);
writer.Key("actor_id");
Serialize(writer, item.actor_id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ObjectTarget& item)
{
writer.StartObject();
writer.Key("unknown");
Serialize(writer, item.unknown);
writer.Key("object_index");
Serialize(writer, item.object_index);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const Reservation& item)
{
writer.StartObject();
writer.Key("number");
Serialize(writer, item.number);
writer.Key("player_id");
Serialize(writer, item.player_id);
writer.Key("player_name");
Serialize(writer, item.player_name);
writer.Key("status");
Serialize(writer, item.status);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ClientLoadout& item)
{
writer.StartObject();
writer.Key("version");
Serialize(writer, item.version);
writer.Key("body");
Serialize(writer, item.body);
writer.Key("skin");
Serialize(writer, item.skin);
writer.Key("wheels");
Serialize(writer, item.wheels);
writer.Key("boost");
Serialize(writer, item.boost);
writer.Key("antenna");
Serialize(writer, item.antenna);
writer.Key("hat");
Serialize(writer, item.hat);
writer.Key("unknown2");
Serialize(writer, item.unknown2);
writer.Key("unknown3");
Serialize(writer, item.unknown3);
writer.Key("engine_audio");
Serialize(writer, item.engine_audio);
writer.Key("trail");
Serialize(writer, item.trail);
writer.Key("goal_explosion");
Serialize(writer, item.goal_explosion);
writer.Key("banner");
Serialize(writer, item.banner);
writer.Key("unknown4");
Serialize(writer, item.unknown4);
writer.Key("unknown5");
Serialize(writer, item.unknown5);
writer.Key("unknown6");
Serialize(writer, item.unknown6);
writer.Key("unknown7");
Serialize(writer, item.unknown7);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const CameraSettings& item)
{
writer.StartObject();
writer.Key("FOV");
Serialize(writer, item.FOV);
writer.Key("height");
Serialize(writer, item.height);
writer.Key("pitch");
Serialize(writer, item.pitch);
writer.Key("distance");
Serialize(writer, item.distance);
writer.Key("stiffness");
Serialize(writer, item.stiffness);
writer.Key("swivelspeed");
Serialize(writer, item.swivelspeed);
writer.Key("transitionspeed");
Serialize(writer, item.transitionspeed);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedPickupData& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("actor_id");
Serialize(writer, item.actor_id);
writer.Key("picked_up");
Serialize(writer, item.picked_up);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedPickupData2& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("actor_id");
Serialize(writer, item.actor_id);
writer.Key("picked_up");
Serialize(writer, item.picked_up);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const TeamPaint& item)
{
writer.StartObject();
writer.Key("team_number");
Serialize(writer, item.team_number);
writer.Key("team_color_id");
Serialize(writer, item.team_color_id);
writer.Key("custom_color_id");
Serialize(writer, item.custom_color_id);
writer.Key("team_finish_id");
Serialize(writer, item.team_finish_id);
writer.Key("custom_finish_id");
Serialize(writer, item.custom_finish_id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedDemolish& item)
{
writer.StartObject();
writer.Key("attacker_flag");
Serialize(writer, item.attacker_flag);
writer.Key("attacker_actor_id");
Serialize(writer, item.attacker_actor_id);
writer.Key("victim_flag");
Serialize(writer, item.victim_flag);
writer.Key("victim_actor_id");
Serialize(writer, item.victim_actor_id);
writer.Key("attacker_velocity");
Serialize(writer, item.attacker_velocity);
writer.Key("victim_velocity");
Serialize(writer, item.victim_velocity);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedDemolish2& item)
{
writer.StartObject();
writer.Key("custom_demo_flag");
Serialize(writer, item.custom_demo_flag);
writer.Key("custom_demo_id");
Serialize(writer, item.custom_demo_id);
writer.Key("attacker_flag");
Serialize(writer, item.attacker_flag);
writer.Key("attacker_actor_id");
Serialize(writer, item.attacker_actor_id);
writer.Key("victim_flag");
Serialize(writer, item.victim_flag);
writer.Key("victim_actor_id");
Serialize(writer, item.victim_actor_id);
writer.Key("attacker_velocity");
Serialize(writer, item.attacker_velocity);
writer.Key("victim_velocity");
Serialize(writer, item.victim_velocity);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const DemolishDataGoalExplosion& item)
{
writer.StartObject();
writer.Key("goal_explosion_owner_flag");
Serialize(writer, item.goal_explosion_owner_flag);
writer.Key("goal_explosion_owner");
Serialize(writer, item.goal_explosion_owner);
writer.Key("attacker_flag");
Serialize(writer, item.attacker_flag);
writer.Key("attacker_actor_id");
Serialize(writer, item.attacker_actor_id);
writer.Key("victim_flag");
Serialize(writer, item.victim_flag);
writer.Key("victim_actor_id");
Serialize(writer, item.victim_actor_id);
writer.Key("attacker_velocity");
Serialize(writer, item.attacker_velocity);
writer.Key("victim_velocity");
Serialize(writer, item.victim_velocity);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedMusicStringer& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("object_index");
Serialize(writer, item.object_index);
writer.Key("trigger");
Serialize(writer, item.trigger);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const GameMode& item)
{
writer.StartObject();
writer.Key("gamemode");
Serialize(writer, item.gamemode);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedStateIndex& item)
{
writer.StartObject();
writer.Key("value");
Serialize(writer, item.value);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const PrivateMatchSettings& item)
{
writer.StartObject();
writer.Key("mutators");
Serialize(writer, item.mutators);
writer.Key("map_name");
Serialize(writer, item.map_name);
writer.Key("max_player_count");
Serialize(writer, item.max_player_count);
writer.Key("game_name");
Serialize(writer, item.game_name);
writer.Key("password");
Serialize(writer, item.password);
writer.Key("is_public");
Serialize(writer, item.is_public);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttribute& item)
{
writer.StartObject();
writer.Key("class_index");
Serialize(writer, item.class_index);
writer.Key("class_name");
Serialize(writer, item.class_name);
writer.Key("value");
Serialize(writer, item.value);
writer.Key("has_value");
Serialize(writer, item.has_value);
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ActorBase& item)
{
writer.StartObject();
writer.Key("value");
Serialize(writer, item.value);
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("unknown2");
Serialize(writer, item.unknown2);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const PartyLeader& item)
{
writer.StartObject();
writer.Key("id");
Serialize(writer, item.id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributeUserColorSingle& item)
{
writer.StartObject();
writer.Key("hasValue");
Serialize(writer, item.hasValue);
writer.Key("value");
Serialize(writer, item.value);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributeUserColorRGB& item)
{
writer.StartObject();
writer.Key("r");
Serialize(writer, item.r);
writer.Key("g");
Serialize(writer, item.g);
writer.Key("b");
Serialize(writer, item.b);
writer.Key("a");
Serialize(writer, item.a);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributeTitle& item)
{
writer.StartObject();
writer.Key("title");
Serialize(writer, item.title);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributeSingleValue& item)
{
writer.StartObject();
writer.Key("value");
Serialize(writer, item.value);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributePainted& item)
{
writer.StartObject();
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributeTeamEdition& item)
{
writer.StartObject();
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ProductAttributeSpecialEdition& item)
{
writer.StartObject();
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const Attributes& item)
{
writer.StartObject();
writer.Key("product_attributes");
Serialize(writer, item.product_attributes);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const OnlineLoadout& item)
{
writer.StartObject();
writer.Key("attributes_list");
Serialize(writer, item.attributes_list);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ClientLoadoutsOnline& item)
{
writer.StartObject();
writer.Key("online_one");
Serialize(writer, item.online_one);
writer.Key("online_two");
Serialize(writer, item.online_two);
writer.Key("loadout_set");
Serialize(writer, item.loadout_set);
writer.Key("is_deprecated");
Serialize(writer, item.is_deprecated);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ClientLoadouts& item)
{
writer.StartObject();
writer.Key("loadout_one");
Serialize(writer, item.loadout_one);
writer.Key("loadout_two");
Serialize(writer, item.loadout_two);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ClubColors& item)
{
writer.StartObject();
writer.Key("team_color_set");
Serialize(writer, item.team_color_set);
writer.Key("team_color_id");
Serialize(writer, item.team_color_id);
writer.Key("custom_color_set");
Serialize(writer, item.custom_color_set);
writer.Key("custom_color_id");
Serialize(writer, item.custom_color_id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const WeldedInfo& item)
{
writer.StartObject();
writer.Key("active");
Serialize(writer, item.active);
writer.Key("actor_id");
Serialize(writer, item.actor_id);
writer.Key("offset");
Serialize(writer, item.offset);
writer.Key("mass");
Serialize(writer, item.mass);
writer.Key("rotation");
Serialize(writer, item.rotation);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedBoostData& item)
{
writer.StartObject();
writer.Key("grant_count");
Serialize(writer, item.grant_count);
writer.Key("boost_amount");
Serialize(writer, item.boost_amount);
writer.Key("unused1");
Serialize(writer, item.unused1);
writer.Key("unused2");
Serialize(writer, item.unused2);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const DamageState& item)
{
writer.StartObject();
writer.Key("damage_state");
Serialize(writer, item.damage_state);
writer.Key("unknown2");
Serialize(writer, item.unknown2);
writer.Key("causer_actor_id");
Serialize(writer, item.causer_actor_id);
writer.Key("damage_location");
Serialize(writer, item.damage_location);
writer.Key("direct_damage");
Serialize(writer, item.direct_damage);
writer.Key("immediate");
Serialize(writer, item.immediate);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const AppliedDamage& item)
{
writer.StartObject();
writer.Key("id");
Serialize(writer, item.id);
writer.Key("position");
Serialize(writer, item.position);
writer.Key("damage_index");
Serialize(writer, item.damage_index);
writer.Key("total_damage");
Serialize(writer, item.total_damage);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedExplosionData& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("actor_id");
Serialize(writer, item.actor_id);
writer.Key("position");
Serialize(writer, item.position);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedExplosionDataExtended& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("actor_id");
Serialize(writer, item.actor_id);
writer.Key("position");
Serialize(writer, item.position);
writer.Key("unknown3");
Serialize(writer, item.unknown3);
writer.Key("secondary_actor_id");
Serialize(writer, item.secondary_actor_id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedTitle& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("unknown2");
Serialize(writer, item.unknown2);
writer.Key("unknown3");
Serialize(writer, item.unknown3);
writer.Key("unknown4");
Serialize(writer, item.unknown4);
writer.Key("unknown5");
Serialize(writer, item.unknown5);
writer.Key("unknown6");
Serialize(writer, item.unknown6);
writer.Key("unknown7");
Serialize(writer, item.unknown7);
writer.Key("unknown8");
Serialize(writer, item.unknown8);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ImpulseData& item)
{
writer.StartObject();
writer.Key("CompressedRotation");
Serialize(writer, item.CompressedRotation);
writer.Key("ImpulseSpeed");
Serialize(writer, item.ImpulseSpeed);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const HistoryKey& item)
{
writer.StartObject();
writer.Key("data");
Serialize(writer, item.data);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const ReplicatedStatEvent& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("object_id");
Serialize(writer, item.object_id);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const RepStatTitle& item)
{
writer.StartObject();
writer.Key("unknown1");
Serialize(writer, item.unknown1);
writer.Key("name");
Serialize(writer, item.name);
writer.Key("object_target");
Serialize(writer, item.object_target);
writer.Key("value");
Serialize(writer, item.value);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const SkillTier& item)
{
writer.StartObject();
writer.Key("tier");
Serialize(writer, item.tier);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const RigidBodyState& item)
{
writer.StartObject();
writer.Key("position");
Serialize(writer, item.position);
writer.Key("lin_vel");
Serialize(writer, item.lin_vel);
writer.Key("quaternion");
Serialize(writer, item.quaternion);
writer.Key("ang_vel");
Serialize(writer, item.ang_vel);
writer.Key("flags");
Serialize(writer, item.flags);
writer.EndObject();
}
template<typename Writer>
inline const void Serialize(Writer& writer, const PickupInfo_TA& item)
{
writer.StartObject();
writer.Key("AvailablePickups");
Serialize(writer, item.AvailablePickups);
writer.Key("unknown");
Serialize(writer, item.unknown);
writer.Key("bItemsArePreview");
Serialize(writer, item.bItemsArePreview);
writer.EndObject();
}
| 17,677
|
C++
|
.h
| 616
| 26.849026
| 88
| 0.775682
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,146
|
OptionsParser.h
|
Bakkes_CPPRP/CPPRPJSON/OptionsParser.h
|
#pragma once
#include <string>
#include <map>
#include <algorithm>
class OptionsParser
{
public:
std::map<std::string, std::string> args;
std::string programName = "";
std::string looseOption = "";
public:
OptionsParser(int argc, char* argv[])
{
programName = std::string(argv[0]);
for (int arg = 1; arg < argc; arg++)
{
std::string key = argv[arg];
if (key.at(0) == '-')
{
if (key.size() >= 2)
{
if (key.at(1) == '-')
{
key = key.substr(2);
}
else
{
key = key.substr(1);
}
}
else
{
continue;
}
}
else
{
looseOption = key;
continue;
}
if (!key.empty())
{
if (arg + 1 < argc && argv[arg + 1][0] != '-')
{
std::string value = argv[arg + 1];
arg++;
args[key] = value;
}
else
{
args[key] = "true";
}
}
}
}
bool HasKey(std::string& key)
{
return args.find(key) != args.end();
}
std::string GetStringValue(std::initializer_list<std::string> optionNames)
{
for (auto it : optionNames)
{
if (HasKey(it))
{
return args[it];
}
}
return "";
}
bool GetBoolValue(std::initializer_list<std::string> optionNames, bool defaultValue)
{
for (auto it : optionNames)
{
if (HasKey(it))
{
std::string val = args[it];
std::transform(val.begin(), val.end(), val.begin(),
[](unsigned char c) { return std::tolower(c); });
return val.compare("1") == 0 || val.compare("true") == 0;
}
}
return defaultValue;
}
int GetIntValue(std::initializer_list<std::string> optionNames, bool defaultValue)
{
for (auto it : optionNames)
{
if (HasKey(it))
{
return std::stoi(args[it]);
}
}
return defaultValue;
}
};
| 1,737
|
C++
|
.h
| 96
| 14.34375
| 85
| 0.573439
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,147
|
SerializeFunctions.h
|
Bakkes_CPPRP/CPPRPJSON/SerializeFunctions.h
|
#pragma once
#include "../CPPRP/data/ReplayFileData.h"
#include "../CPPRP/data/NetworkData.h"
#include <cstdint>
#include <vector>
#include <unordered_map>
#include <functional>
#include <memory>
#include <variant>
//#define RAPIDJSON_SIMD 1
#define RAPIDJSON_HAS_STDSTRING 1
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
namespace CPPRP
{
namespace JSON
{
template<typename Writer, typename T>
static inline const void Serialize(Writer& writer, const T& item)
{
//std::stringstream ss;
//ss << "unsupported " << typeid(T).name();
//std::string o = ss.str();
//printf("%s\n", o.c_str());
//assert(1 == 2);
writer.String("");// (o.c_str(), o.size());
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const uint64_t& item)
{
char tmp[21], buf[21];
char *tempPos = tmp;
uint64_t q = item;
do {
*tempPos++ = "0123456789"[ q % 10 ];
q /= 10;
} while ( q );
char *bufPos = buf;
while(tempPos != tmp)
{
*bufPos++ = *--tempPos;
}
*bufPos = '\0';
writer.String(buf);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const int64_t& item)
{
//Unoptimized since I don't think this is called much
const std::string str = std::to_string(item);
writer.String(str.c_str());
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const uint8_t& item)
{
writer.Uint(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const char& item)
{
writer.Int((int)item);
}
template<typename Writer, int DEC=0>
static inline const void Serialize(Writer& writer, const float& item)
{
if constexpr (DEC == 45343452)
{
char buf[20];
char tmp[20];
bool isNeg = item < 0.f;
int value = static_cast<int>((item * 100.f) + (isNeg ? -.5f : 0.5f));
char* tmpPos = tmp;
if(isNeg)
{
value *= -1;
}
*tmpPos++ = 48 + (value % 10);
value /= 10;
*tmpPos++ = 48 + (value % 10);
value /= 10;
*tmpPos++ = '.';
*tmpPos++ = 48 + (value % 10);
value /= 10;
while (value)
{
//printf("value: %i\n", value);
*tmpPos++ = 48 + (value % 10); //"0123456789"[ value % 10 ];
value /= 10;
}
//printf("----\n");
if(isNeg)
{
*tmpPos++ = '-';
}
char *bufPos = buf;
while(tmpPos != tmp)
{
*bufPos++ = *--tmpPos;
}
//*bufPos++ = '.';
//*bufPos++ = 48 + (value / 10);
//*bufPos++ = 48 + (value % 10);
//*bufPos = '\0';
writer.RawValue(buf, (bufPos - buf), rapidjson::kNumberType);
}
else
{
writer.Double(item);
}
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const std::string& item)
{
writer.String(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const uint16_t& item)
{
writer.Uint(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const uint32_t& item)
{
writer.Uint(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const int8_t& item)
{
writer.Int(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const int16_t& item)
{
writer.Int(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const int32_t& item)
{
writer.Int(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const bool& item)
{
writer.Bool(item);
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const Vector3& item)
{
/*char data[42] = "{\"X\":00000.00, \"Y\":00000.00, \"Z\":00000.00";
int xabs = ((item.x < 0 ? -item.x : item.x) + 0.5f) * 100;
data[5] = item.x < 0 ? '-' : ' ';
data[6] = 48 + (xabs) / 100000;
data[7] = 48 + (xabs % 100000) / 10000;
data[8] = 48 + (xabs % 10000) / 1000;
data[9] = 48 + (xabs % 1000) / 100;
data[11] = 48 + (xabs % 100) / 10;
data[12] = 48 + (xabs % 10) / 1;
int yabs = ((item.y < 0 ? -item.y : item.y) + 0.5f) * 100;
data[19] = item.y < 0 ? '-' : ' ';
data[20] = 48 + (yabs) / 100000;
data[21] = 48 + (yabs % 100000) / 10000;
data[22] = 48 + (yabs % 10000) / 1000;
data[23] = 48 + (yabs % 1000) / 100;
data[25] = 48 + (yabs % 100) / 10;
data[26] = 48 + (yabs % 10) / 1;
int zabs = ((item.z < 0 ? -item.z : item.z) + 0.5f) * 100;
data[33] = item.z < 0 ? '-' : ' ';
data[34] = 48 + (zabs) / 100000;
data[35] = 48 + (zabs % 100000) / 10000;
data[36] = 48 + (zabs % 10000) / 1000;
data[37] = 48 + (zabs % 1000) / 100;
data[39] = 48 + (zabs % 100) / 10;
data[40] = 48 + (zabs % 10) / 1;
data[41] = '}';
writer.RawValue(data, 42, rapidjson::kObjectType);*/
writer.StartObject();
writer.Key("X");
//writer.StartArray();
Serialize<Writer, 2>(writer, item.x);
//writer.Double(item.x);
//writer.EndArray();
writer.Key("Y");
//writer.StartArray();
Serialize<Writer, 2>(writer, item.y);
//writer.Double(item.y);
//writer.EndArray();
//Serialize<Writer, 2>(writer, item.y);
writer.Key("Z");
//writer.StartArray();
Serialize<Writer, 2>(writer, item.z);
//writer.Double(item.z);
//writer.EndArray();
//Serialize<Writer, 2>(writer, item.z);
writer.EndObject();
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const Vector3I& item)
{
writer.StartObject();
writer.Key("X");
Serialize<Writer>(writer, item.x);
writer.Key("Y");
Serialize<Writer>(writer, item.y);
writer.Key("Z");
Serialize<Writer>(writer, item.z);
writer.EndObject();
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const struct Quat& item)
{
writer.StartObject();
writer.Key("X");
Serialize<Writer>(writer, item.x);
writer.Key("Y");
Serialize<Writer>(writer, item.y);
writer.Key("Z");
Serialize<Writer>(writer, item.z);
writer.Key("W");
Serialize<Writer>(writer, item.w);
writer.EndObject();
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const Rotator& item)
{
writer.StartObject();
writer.Key("Pitch");
Serialize<Writer>(writer, item.pitch);
writer.Key("Yaw");
Serialize<Writer>(writer, item.yaw);
writer.Key("Roll");
Serialize<Writer>(writer, item.roll);
writer.EndObject();
}
template<typename Writer, typename T>
static inline const void Serialize(Writer& writer, const std::vector<T>& item) {
writer.StartArray();
const size_t size = item.size();
for (size_t i = 0; i < size; ++i)
{
Serialize(writer, item.at(i));
}
writer.EndArray();
}
template<typename Writer>
static inline const void Serialize(Writer& writer, const CPPRP::OnlineID item)
{
writer.StartObject();
std::visit(
[&](const UniqueId& base)
{
writer.Key("Platform");
Serialize<Writer>(writer, base.platform);
writer.Key("SplitscreenID");
Serialize<Writer>(writer, base.splitscreenID);
},
item);
writer.Key("UniqueID");
if (auto steamId = std::get_if<CPPRP::SteamID>(&item))
{
Serialize<Writer>(writer, steamId->steamID);
//writer.Uint64(steamId->steamID);
}
else if (auto epicId = std::get_if<CPPRP::EpicID>(&item))
{
Serialize<Writer>(writer, epicId->epicId);
}
else if (auto xboxId = std::get_if<CPPRP::XBoxID>(&item))
{
Serialize<Writer>(writer, xboxId->xboxID);
}
else if (auto switchId = std::get_if<CPPRP::SwitchID>(&item))
{
writer.StartArray();
Serialize<Writer>(writer, switchId->a);
Serialize<Writer>(writer, switchId->b);
Serialize<Writer>(writer, switchId->c);
Serialize<Writer>(writer, switchId->d);
writer.EndArray();
}
else if (auto ps4Id = std::get_if<CPPRP::PS4ID>(&item))
{
Serialize<Writer>(writer, ps4Id->psId);
writer.Key("PlayerName");
Serialize<Writer>(writer, ps4Id->playerName);
writer.Key("Unknown1");
Serialize<Writer>(writer, ps4Id->unknown1);
writer.Key("Unknown2");
Serialize<Writer>(writer, ps4Id->unknown2);
}
else if (auto psynetId = std::get_if<CPPRP::PsyNetID>(&item))
{
writer.StartArray();
Serialize<Writer>(writer, psynetId->a);
Serialize<Writer>(writer, psynetId->b);
Serialize<Writer>(writer, psynetId->c);
Serialize<Writer>(writer, psynetId->d);
writer.EndArray();
}
else if (auto qqId = std::get_if<CPPRP::QQID>(&item))
{
Serialize<Writer>(writer, qqId->qqID);
}
else if (auto epicId = std::get_if<CPPRP::EpicID>(&item))
{
Serialize<Writer>(writer, epicId->epicId);
}
else
{
Serialize<Writer>(writer, 1337);
}
writer.EndObject();
}
#include "GeneratedSerializeFunctions.h"
template<typename Writer>
class Serializer
{
public:
typedef std::function<void(Writer&, std::shared_ptr<Engine::Actor>&)> writerFunc;
std::unordered_map<std::string, writerFunc> writerFuncMap;
std::vector<writerFunc> writerFuncs;
template<typename T>
inline void RegisterSerializer(const std::string& str, T callback)
{
writerFuncMap[str] = callback;
}
Serializer()
{
#define fulln(namesp, classn, propname) xstr(namesp) "." xstr(classn) ":" xstr(propname)
#define GAMEFIELD(namesp, classn, propname, nameoftype) \
RegisterSerializer(fulln(namesp, classn, propname), [](Writer& writer, std::shared_ptr<Engine::Actor>& struc) { writer.Key(fulln(namesp, classn, propname)); Serialize<Writer>(writer, std::static_pointer_cast<CPPRP::namesp::classn>(struc)->propname); })
#include "../CPPRP/generated/GameClassMacros.h"
#undef fulln
#undef GAMEFIELD
}
};
};
};
| 9,886
|
C++
|
.h
| 338
| 25.248521
| 253
| 0.639261
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,148
|
CPPRPJSON.h
|
Bakkes_CPPRP/CPPRPJSON/CPPRPJSON.h
|
#pragma once
#pragma comment(lib, "CPPRP.lib")
#include "../CPPRP/ReplayFile.h"
#include "SerializeFunctions.h"
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
#include <algorithm>
#include <map>
#include <filesystem>
#include <queue>
#include <unordered_map>
#include <fstream>
#include "OptionsParser.h"
#include "rapidjson/filewritestream.h"
#undef max
//static int a = serializer.Test();
struct UpdateData
{
const CPPRP::ActorStateData asd;
const std::vector<uint32_t> props;
};
template<typename Writer>
void SerializeProp(Writer& writer, const std::string& name, std::shared_ptr<CPPRP::Property>& currentProperty, const bool specialByteProp)
{
writer.String(name.c_str());
switch (currentProperty->property_type[0])
{
case 'N':
{
if (currentProperty->property_type[1] == 'o') //Type is "None"
{
writer.Null();
}
else //Type is "Name"
{
writer.String(std::get<std::string>(currentProperty->value).c_str());
}
}
break;
case 'I': //IntProperty
{
writer.Int(std::get<int32_t>(currentProperty->value));
}
break;
case 'S': //StringProperty
{
if (currentProperty->property_type[3] == 'u') //Type is "StructProperty"
{
auto& structProp = std::get<CPPRP::StructProperty>(currentProperty->value);
writer.StartObject();
writer.String("Name");
writer.String(structProp.name);
writer.String("Fields");
writer.StartArray();
for (auto& field : structProp.fields)
{
writer.StartObject();
SerializeProp(writer, field->property_name, field, specialByteProp);
writer.EndObject();
}
writer.EndArray();
writer.EndObject();
}
else
{
writer.String(std::get<std::string>(currentProperty->value).c_str());
}
}
break;
case 'B':
{
if (currentProperty->property_type[1] == 'y') //Type is "ByteProperty"
{
CPPRP::EnumProperty ep = std::get<CPPRP::EnumProperty>(currentProperty->value);
writer.StartObject();
writer.String("Type");
writer.String(ep.type.c_str());
writer.String("Value");
if (uint8_t* val = std::get_if<uint8_t>(&ep.value))
{
writer.Int(*val);
}
else if (std::string* val = std::get_if<std::string>(&ep.value))
{
writer.String(val->c_str());
}
else
{
writer.String("ERROR!!");
assert(1 == 2);
}
writer.EndObject();
}
else //Type is "BoolProperty", but unlike network data, is stored as entire byte
{
if (specialByteProp)
{
writer.Int(std::get<uint32_t>(currentProperty->value));
}
else
{
writer.Int(std::get<uint8_t>(currentProperty->value));
}
}
}
break;
case 'Q': //QWordProperty
{
writer.String(std::to_string(std::get<uint64_t>(currentProperty->value)));
}
break;
case 'F': //FloatProperty
{
writer.Double(std::get<float>(currentProperty->value));
}
break;
case 'A': //ArrayProperty
{
auto temp = (std::get<std::vector<std::unordered_map<std::string, std::shared_ptr<CPPRP::Property>>>>(currentProperty->value));
writer.StartArray();
for (auto& wot : temp)
{
writer.StartObject();
for (auto& wot2 : wot)
{
SerializeProp(writer, wot2.first, wot2.second, specialByteProp);
}
writer.EndObject();
}
writer.EndArray();
}
break;
default: //Die
writer.Null();
//assert(1 == 2);
break;
}
}
template<typename Writer>
int SerializeReplay(Writer& writer, const std::shared_ptr<CPPRP::ReplayFile>& replayFile, const bool parseBody)
{
/*replayFile->Parse();
return 0;*/
auto serializer = CPPRP::JSON::Serializer<Writer>();
std::vector<CPPRP::ActorStateData> createdActorsThisTick;
std::vector<CPPRP::ActorStateData> deletedActorsThisTick;
std::vector<UpdateData> updatedActorsThisTick;
const auto headerData = replayFile->replayFile;
writer.StartObject();
writer.String("Replay");
writer.StartObject();
writer.String("Header");
writer.StartObject();
writer.String("EngineVersion");
writer.Uint(headerData->header.engineVersion);
writer.String("LicenseeVersion");
writer.Uint(headerData->header.licenseeVersion);
writer.String("NetVersion");
writer.Uint(headerData->header.netVersion);
writer.String("CRC");
writer.Uint(headerData->header.crc);
writer.String("Size");
writer.Uint(headerData->header.size);
writer.String("ReplayType");
writer.String(headerData->replayType.c_str());
writer.String("Properties");
const bool useSpecialByteProp = headerData->header.engineVersion == 0 &&
headerData->header.licenseeVersion == 0 &&
headerData->header.netVersion == 0;
writer.StartObject();
for (auto prop : headerData->properties)
{
SerializeProp(writer, prop.first, prop.second, useSpecialByteProp);
}
writer.EndObject();
writer.String("Keyframes");
writer.StartArray();
for (auto kv : headerData->keyframes)
{
writer.StartObject();
writer.String("Time");
writer.Double(kv.time);
writer.String("Frame");
writer.Uint(kv.frame);
writer.String("Filepos");
writer.Uint(kv.filepos);
writer.EndObject();
}
writer.EndArray();
writer.String("ReplayLog");
writer.StartArray();
for (auto kv : headerData->debugstrings)
{
writer.StartObject();
writer.String("Frame");
writer.Int(kv.frame);
writer.String("Key");
writer.String(kv.key);
writer.String("Value");
writer.String(kv.value);
writer.EndObject();
}
writer.EndArray();
writer.EndObject();
writer.String("Body");
replayFile->createdCallbacks.push_back([&](const CPPRP::ActorStateData& asd)
{
createdActorsThisTick.push_back(asd);
});
replayFile->actorDeleteCallbacks.push_back([&](const CPPRP::ActorStateData& asd)
{
deletedActorsThisTick.push_back(asd);
});
replayFile->updatedCallbacks.push_back([&](const CPPRP::ActorStateData& asd, const std::vector<uint32_t>& props)
{
updatedActorsThisTick.push_back({ asd, props });
});
replayFile->tickables.push_back([&](const CPPRP::Frame frame, const std::unordered_map<uint32_t, CPPRP::ActorStateData>& actorStats)
{
writer.StartObject();
writer.String("Frame");
writer.Uint(frame.frameNumber);
writer.String("Time");
writer.Double(frame.time);
writer.String("Delta");
writer.Double(frame.delta);
writer.String("Created");
writer.StartArray();
for (auto& created : createdActorsThisTick)
{
writer.StartObject();
writer.String("Id");
writer.Uint(created.actorId);
std::string name = replayFile->replayFile->names.at(created.nameId);
std::string className = replayFile->replayFile->objects.at(created.classNameId);
writer.String("Name");
writer.String(name);
writer.String("ClassName");
writer.String(className);
bool hasInitialPosition = replayFile->HasInitialPosition(created.nameId);
writer.String("HasInitialPosition");
writer.Bool(hasInitialPosition);
if (hasInitialPosition)
{
writer.String("InitialPosition");
CPPRP::JSON::Serialize<Writer>(writer, created.actorObject->Location);
}
bool hasInitialRotation = replayFile->HasRotation(created.nameId);
writer.String("HasInitialRotation");
writer.Bool(hasInitialRotation);
if (hasInitialRotation)
{
writer.String("InitialRotation");
CPPRP::JSON::Serialize<Writer>(writer, created.actorObject->Rotation);
}
writer.EndObject();
}
writer.EndArray();
writer.String("Deleted");
writer.StartArray();
for (auto& deleted : deletedActorsThisTick)
{
writer.Uint(deleted.actorId);
}
writer.EndArray();
writer.String("Updated");
writer.StartArray();
for (auto& updated : updatedActorsThisTick)
{
writer.StartObject();
writer.String("Id");
writer.Uint(updated.asd.actorId);
writer.String("UpdatedProperties");
writer.StartArray();
for (auto& updatedProp : updated.props)
{
writer.StartObject();
//std::string objectName = replayFile->replayFile->objects[updatedProp];
std::shared_ptr<CPPRP::Engine::Actor> a = updated.asd.actorObject;
serializer.writerFuncs[updatedProp](writer, a);
writer.EndObject();
}
writer.EndArray();
writer.EndObject();
}
writer.EndArray();
writer.EndObject();
createdActorsThisTick.clear();
updatedActorsThisTick.clear();
deletedActorsThisTick.clear();
});
writer.StartArray();
try
{
if (parseBody)
{
const size_t objectsSize = replayFile->replayFile->objects.size();
serializer.writerFuncs.resize(objectsSize);
for (size_t i = 0; i < objectsSize; i++)
{
const std::string& name = replayFile->replayFile->objects.at(i);
auto found = serializer.writerFuncMap.find(name);
if (found != serializer.writerFuncMap.end())
{
serializer.writerFuncs[i] = found->second;
}
}
replayFile->Parse();
}
}
catch (const CPPRP::InvalidVersionException& e)
{
std::cerr << "InvalidVersionException: " << e.what() << " on file " << replayFile->path << "\n";
return 1;
}
catch (const CPPRP::PropertyDoesNotExistException& e)
{
std::cerr << "PropertyDoesNotExistException: " << e.what() << " on file " << replayFile->path << "\n";
return 1;
}
catch (const CPPRP::AttributeParseException<uint32_t>& e)
{
std::cerr << "AttributeParseException: " << e.what() << " on file " << replayFile->path << "\n";
return 1;
}
catch (const CPPRP::GeneralParseException<uint32_t>& e)
{
std::cerr << "GeneralParseException: " << e.what() << " on file " << replayFile->path << "\n";
return 1;
}
catch (const std::exception& e) //e
{
std::cerr << "GeneralException: " << e.what() << " on file " << replayFile->path.filename() << "\n";
return 1;
}
catch (...)
{
std::cerr << "UnknownException: on file " << replayFile->path.filename() << "\n";
return 1;
}
writer.EndArray();
writer.EndObject();
writer.EndObject();
return 0;
}
template<typename Writer>
int ParseBodyAndSerializeReplay(Writer& writer, const std::shared_ptr<CPPRP::ReplayFile>& replayFile, const bool parseBody, int precision)
{
if (precision > 0)
{
writer.SetMaxDecimalPlaces(precision);
}
return SerializeReplay(writer, replayFile, parseBody);
}
| 10,133
|
C++
|
.h
| 357
| 24.890756
| 138
| 0.695643
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,149
|
animator.h
|
AKJ7_TM1637/src/animator.h
|
#ifndef TM1637_ANIMATOR_H
#define TM1637_ANIMATOR_H
#include <Arduino.h>
#include "type_traits.h"
#include "mI2C.h"
class Animator {
struct Tasker {
using duration_type = uint32_t;
void reset(duration_type delay, duration_type start) {
delay_ = delay;
start_ = start;
}
bool check() {
auto current = millis();
if (current - start_ > delay_) {
start_ = current;
return true;
}
return false;
}
private:
duration_type delay_;
duration_type start_;
};
friend class TM1637;
enum class DataCommand_e : uint8_t {
FIXED_ADDRESS = 0x44,
AUTOMATIC_ADDRESS_ADDING = 0x40,
READ_KEY_SCAN_DATA = 0x42,
WRITE_DATA_TO_DISPLAY_REGISTER = 0x40,
NORMAL_MODE = 0x40,
TESTING_MODE = 0x48
};
enum class AddressCommand_e : uint8_t {
C0H = 0xC0,
C1H,
C2H,
C3H,
C4H,
C5H,
C6H // Ignore scan
};
enum class Animation : int8_t {
NONE,
BLINK,
FADE_OUT,
FADE_IN,
SCROLL_LEFT
};
public:
enum class DisplayControl_e : uint8_t {
PULSE_WIDTH_1_16 = 0x88,
PULSE_WIDTH_2_16,
PULSE_WIDTH_4_16,
PULSE_WIDTH_10_16,
PULSE_WIDTH_11_16,
PULSE_WIDTH_12_16,
PULSE_WIDTH_13_16,
PULSE_WIDTH_14_16,
DISPLAY_OFF = 0x80,
DISPLAY_ON = PULSE_WIDTH_1_16
};
/**
* @brief Construct an animator object to manage the low-level transfer to the display device
* @param clkPin Port number of the Clock pin
* @param dataPin Port number of the Data pin
* @param totalDigits Total number of digits the device supports
*/
Animator(uint8_t clkPin, uint8_t dataPin, uint8_t totalDigits) : mi2C_(clkPin, dataPin),
totalDigits_{totalDigits} {}
/**
* @brief Run the blinking animation in periodic intervals
* @param delay Duration in-between animations in seconds
*/
void blink(Tasker::duration_type delay) {
static DisplayControl_e savedBrightness;
if (currentAnimation == Animation::BLINK) {
if (tasker.check()) {
brightness_ =
brightness_ != DisplayControl_e::DISPLAY_OFF ? DisplayControl_e::DISPLAY_OFF : savedBrightness;
refresh();
}
return;
}
savedBrightness = brightness_;
tasker.reset(delay, millis());
currentAnimation = Animation::BLINK;
}
/**
* @brief Run the fade-out animation in periodic intervals
* @param delay Duration in-between animations in seconds
*/
void fadeOut(Tasker::duration_type delay) {
if (currentAnimation == Animation::FADE_OUT) {
if (tasker.check()) {
auto current = control2Int(brightness_);
if (current > 0) --current;
brightness_ = fetchControl(current);
refresh();
}
return;
}
tasker.reset(delay, millis());
currentAnimation = Animation::FADE_OUT;
}
/**
* @brief Run the fade-in animation in periodic intervals
* @param delay Duration in-between animations in seconds
*/
void fadeIn(Tasker::duration_type delay) {
if (currentAnimation == Animation::FADE_IN) {
if (tasker.check()) {
if (brightness_ == DisplayControl_e::PULSE_WIDTH_14_16)
return;
auto current = control2Int(brightness_);
current++;
brightness_ = fetchControl(current);
refresh();
}
return;
}
tasker.reset(delay, millis());
currentAnimation = Animation::FADE_IN;
}
/**
* @brief Run the scroll-left animation in periodic intervals
* @param delay Duration in-between animations in seconds
*/
void scrollLeft(Tasker::duration_type delay) {
if (currentAnimation == Animation::SCROLL_LEFT) {
if (tasker.check()) {
static unsigned int index = 0;
if (index > buffer_.length()) {
currentAnimation = Animation::NONE;
index = 0;
return;
}
String s(buffer_.substring(index, buffer_.length()));
++index;
for (size_t counter = s.length(); counter < totalDigits_; ++counter)
s.concat(static_cast<char>(0x00));
sendToDisplay<DataCommand_e::AUTOMATIC_ADDRESS_ADDING, AddressCommand_e::C0H>(
brightness_,
reinterpret_cast<const uint8_t *>(s.c_str()),
static_cast<size_t>(min((unsigned int) totalDigits_, s.length())));
}
return;
}
tasker.reset(delay, millis());
currentAnimation = Animation::SCROLL_LEFT;
}
/**
* @brief Turn the display off but keep the internal cache and data intact.
*/
void off() const {
sendToDisplay<DataCommand_e::FIXED_ADDRESS, AddressCommand_e::C6H>(DisplayControl_e::DISPLAY_OFF);
}
/**
* @brief Set the brightness level of the display device
* @param brightness Pulse frequency equivalent to the brightness of the device
*/
void on(DisplayControl_e brightness) const {
sendToDisplay<DataCommand_e::FIXED_ADDRESS, AddressCommand_e::C6H>(brightness);
}
/**
* @brief Reset, refill the data buffer of the display
* @param value Buffer to fill the display's buffer with
*/
void reset(const String &value) {
buffer_ = "";
for (decltype(value.length()) counter{}; counter < value.length(); ++counter) {
auto d = toDisplayDigit(value[counter]);
if (d == 0x80u && buffer_.length() > 0) {
buffer_[buffer_.length() - 1] |= static_cast<char>(0x80u);
} else
buffer_.concat(static_cast<char>(d));
}
}
/**
* @brief Cancel all animation. Set the display to the normal state.
*/
inline void resetAnimation() noexcept {
currentAnimation = Animation::NONE;
}
/**
* @brief Clear the display's internal buffer, reset the state of colon and display 0x00
* to the screen
*/
void clear() {
buffer_ = "";
for (size_t counter{}; counter < totalDigits_; ++counter)
buffer_.concat(static_cast<char>(0x00u));
dp_ = 0;
colon_ = 0;
resetAnimation();
refresh();
}
/**
* @brief Transfer the display's data buffer to the display device
*/
void refresh() {
sendToDisplay<DataCommand_e::AUTOMATIC_ADDRESS_ADDING, AddressCommand_e::C0H>(
brightness_,
reinterpret_cast<const uint8_t *>(buffer_.c_str()),
static_cast<size_t>(min((unsigned int) totalDigits_, buffer_.length())));
}
private:
inline uint8_t toDisplayDigit(signed char c) noexcept {
return c < 0 ? 0x00 : ascii[static_cast<unsigned>(c)];
}
static inline uint8_t control2Int(DisplayControl_e e) noexcept {
auto temp = static_cast<int>(e) - 0x87;
return temp > 0 ? static_cast<uint8_t>(temp) : 0x00;
}
static inline float control2Percent(DisplayControl_e control) noexcept {
if (control == DisplayControl_e::DISPLAY_OFF) {
return 0;
}
uint8_t indexes[] = {1, 2, 4, 10, 11, 12, 13, 14};
auto controlInt = static_cast<uint8_t>(control) - static_cast<uint8_t>(DisplayControl_e::PULSE_WIDTH_1_16);
return (static_cast<float>(indexes[controlInt]) / 16) * 100.0f;
}
static inline DisplayControl_e fetchControl(uint8_t value) noexcept {
#define CASER(val0, val1) \
case val0: \
return DisplayControl_e::val1;
switch (value) {
CASER(0, DISPLAY_OFF)
CASER(1, PULSE_WIDTH_1_16)
CASER(2, PULSE_WIDTH_2_16)
CASER(3, PULSE_WIDTH_4_16)
CASER(4, PULSE_WIDTH_10_16)
CASER(5, PULSE_WIDTH_11_16)
CASER(6, PULSE_WIDTH_12_16)
CASER(7, PULSE_WIDTH_13_16)
default:
return DisplayControl_e::PULSE_WIDTH_14_16;
}
#undef CASER
}
static inline DisplayControl_e fetchControlPercent(float value) noexcept {
DisplayControl_e displayControls[] = {DisplayControl_e::DISPLAY_OFF, DisplayControl_e::PULSE_WIDTH_1_16,
DisplayControl_e::PULSE_WIDTH_2_16, DisplayControl_e::PULSE_WIDTH_4_16,
DisplayControl_e::PULSE_WIDTH_10_16, DisplayControl_e::PULSE_WIDTH_11_16,
DisplayControl_e::PULSE_WIDTH_12_16, DisplayControl_e::PULSE_WIDTH_13_16,
DisplayControl_e::PULSE_WIDTH_14_16};
for (auto control : displayControls) {
if (value <= control2Percent(control)) {
return control;
}
}
return DisplayControl_e::PULSE_WIDTH_14_16;
}
template<DataCommand_e DATA_COMMAND, AddressCommand_e ADDRESS_COMMAND>
void sendToDisplay(DisplayControl_e displayControl) const noexcept {
mi2C_.beginTransmission();
mi2C_.send(static_cast<uint8_t>(DATA_COMMAND));
mi2C_.endTransmission();
mi2C_.beginTransmission();
mi2C_.send(static_cast<uint8_t>(ADDRESS_COMMAND));
mi2C_.endTransmission();
mi2C_.beginTransmission();
mi2C_.send(static_cast<uint8_t>(displayControl));
mi2C_.endTransmission();
}
template<DataCommand_e DATA_COMMAND, AddressCommand_e ADDRESS_COMMAND>
void sendToDisplay(DisplayControl_e displayControl, const uint8_t *values, size_t size) const noexcept {
mi2C_.beginTransmission();
mi2C_.send(static_cast<uint8_t>(DATA_COMMAND));
mi2C_.endTransmission();
mi2C_.beginTransmission();
mi2C_.send(static_cast<uint8_t>(ADDRESS_COMMAND));
for (decltype(size) counter{}; counter < size; ++counter)
mi2C_.send((colon_ || (dp_ & (1u << counter))) ? values[counter] | 0x80u : values[counter]);
mi2C_.endTransmission();
mi2C_.beginTransmission();
mi2C_.send(static_cast<uint8_t>(displayControl));
mi2C_.endTransmission();
}
String buffer_ = "";
MI2C mi2C_;
DisplayControl_e brightness_ = DisplayControl_e::DISPLAY_ON;
uint8_t dp_;
uint8_t colon_;
const uint8_t totalDigits_;
Tasker tasker;
Animation currentAnimation = Animation::NONE;
const uint8_t ascii[128] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x22, 0x00, 0x6D, 0x00, 0x00, 0x20,
0x39, 0x0F, 0x00, 0x00, 0x10, 0x40, 0x80, 0x52, 0x3F, 0x06,
0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x00, 0x00,
0x00, 0x48, 0x00, 0x53, 0x00, 0x77, 0x7C, 0x39, 0x5E, 0x79,
0x71, 0x3D, 0x76, 0x30, 0x1E, 0x00, 0x38, 0x00, 0x54, 0x3F,
0x73, 0x67, 0x50, 0x6D, 0x78, 0x3E, 0x00, 0x00, 0x00, 0x6E,
0x5B, 0x39, 0x64, 0x00, 0x0F, 0x08, 0x20, 0x77, 0x7C, 0x58,
0x5E, 0x79, 0x71, 0x3D, 0x74, 0x04, 0x1E, 0x00, 0x38, 0x00,
0x54, 0x5C, 0x73, 0x67, 0x50, 0x6D, 0x78, 0x3E, 0x00, 0x00,
0x00, 0x6E, 0x5B, 0x39, 0x30, 0x0F, 0x40, 0x00,
};
};
#endif //TM1637_ANIMATOR_H
| 12,076
|
C++
|
.h
| 305
| 29.203279
| 119
| 0.568313
|
AKJ7/TM1637
| 31
| 10
| 3
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,151
|
TM1637.h
|
AKJ7_TM1637/src/TM1637.h
|
#ifndef TM1637_TM1637_H
#define TM1637_TM1637_H
#include <Arduino.h>
#include "type_traits.h"
#include "animator.h"
#ifndef TM1637_LEGACY
#define TM1637_LEGACY 1
#endif
#if __GNUC__ >= 3
#define DEPRECATED __attribute__((deprecated))
#else
#define DEPRECATED
#endif
/**
* @brief Interface to help build single segment in a functional
* way
*
* @details A single 7-Segment display is structured as followed:
* -- A --
* | |
* F B
* | |
* -- G --
* | |
* E C
* | |
* -- D -- -Dot-
*/
struct DisplayDigit {
/**
* @brief Set the A segment
* @return self
*/
DisplayDigit &setA() {
value |= 0x01;
return *this;
}
/**
* @brief Set the B segment
* @return self
*/
DisplayDigit &setB() {
value |= 0x02;
return *this;
}
/**
* @brief Set the C segment
* @return self
*/
DisplayDigit &setC() {
value |= 0x04;
return *this;
}
/**
* @brief Set the D segment
* @return self
*/
DisplayDigit &setD() {
value |= 0x08;
return *this;
}
/**
* @brief Set the E segment
* @return self
*/
DisplayDigit &setE() {
value |= 0x10;
return *this;
}
/**
* @brief Set the F segment
* @return self
*/
DisplayDigit &setF() {
value |= 0x20;
return *this;
}
/**
* @brief Set the G segment
* @return self
*/
DisplayDigit &setG() {
value |= 0x40;
return *this;
}
/**
* @brief Set the Dot segment
* @return self
*/
DisplayDigit &setDot() {
value |= 0x80;
return *this;
}
/**
* Allow implicit static casting to uint8_t
* @return Encoded digit in byte
*/
operator uint8_t() const { return value; }
/**
* Allow implicit conversion from uint8_t
* @param rhs Already encoded byte as uint8_t
* @return self
*/
DisplayDigit &operator=(uint8_t rhs) {
value = rhs;
return *this;
}
uint8_t value{};
};
/**
* @brief Facade to the underlying access to the display device
* @details Wrapper to the low-level functions
*/
class TM1637 {
friend Animator;
public:
static constexpr uint8_t TOTAL_DIGITS = 4;
/**
* @brief Construct a TM1637 Instance
* @param clkPin Port number of the connected display CLK pin
* @param dataPin Port number of the connected display DATA pin
*/
TM1637(uint8_t clkPin, uint8_t dataPin) noexcept: animator_(clkPin, dataPin, TOTAL_DIGITS) {};
/**
* Deleted Copy Constructor
*/
TM1637(const TM1637 &) = delete;
/**
* Deleted Copy Assign Constructor
*/
TM1637 &operator=(const TM1637 &) = delete;
/**
* Default Destructor
*/
~TM1637() = default;
/**
* Initialise the low-level communication with the display device
*/
void begin() {
animator_.mi2C_.begin();
offMode();
};
/**
* Alias for `TM1637::begin()`
*/
inline void init() { begin(); }
/**
* Send the underlying display buffer to the display device
* @return Current instance of the animator
*/
inline Animator *refresh() {
animator_.refresh();
return &animator_;
}
/**
* Print/Display some values on the display
* @param value Content to display
* @param overflow Cache more characters than the display allows. Useful for scrolling
* @param pad Fill the unoccupied 7-segments displays with 0
* @param offset Start Position to display from
* @return Current instance of the animator
*/
template<typename T>
typename type_traits::enable_if<
type_traits::is_string<T>::value ||
type_traits::is_floating_point<T>::value ||
type_traits::is_integral<T>::value,
Animator *>::type
display(const T value, bool overflow = true, bool pad = false, uint8_t offset = 0) {
String temp = stringer<T>(value);
if (temp == cache_)
return &animator_;
cache_ = temp;
String cache;
cache = "";
for (decltype(offset) counter{}; counter < offset; ++counter) {
cache.concat(static_cast<char>(0x00));
}
cache.concat(temp);
if (pad) {
for (size_t counter = cache.length(); counter < animator_.totalDigits_; ++counter) {
cache.concat(static_cast<char>('O'));
}
}
if (!overflow) {
cache.substring(0, animator_.totalDigits_);
}
animator_.reset(cache);
return refresh();
}
/**
* @brief Display raw bytes (already encoded binaries) to the display
* @warning The buffer is not cached
* @param buffer The data to display
* @param size Size to the data to display
* @return Instance of the current animator
*/
Animator *displayRawBytes(const uint8_t *buffer, size_t size) {
cache_ = "";
animator_.buffer_ = "";
for (decltype(size) counter{}; counter < size; ++counter) {
animator_.buffer_.concat(static_cast<char>(buffer[counter]));
}
return refresh();
}
/**
* @brief Turn display off
* @return Instance of the current animator
*/
inline Animator *offMode() noexcept {
animator_.off();
return &animator_;
};
/**
* @brief Turn display on
* @return Instance of the current animator
*/
inline Animator *onMode() noexcept {
animator_.on(animator_.brightness_);
return &animator_;
};
/**
* @brief Turn the colon off
* @note This feature is not supported by all TM1637 displays
* @return Instance of the current animator
*/
inline Animator *colonOff() noexcept {
animator_.colon_ = false;
animator_.refresh();
return &animator_;
};
/**
* @brief Turn the colon on
* @note This feature is not supported by all TM1637 displays
* @return Instance of the current animator
*/
inline Animator *colonOn() noexcept {
animator_.colon_ = true;
animator_.refresh();
return &animator_;
};
/**
* @brief Toggle the state of the colon
* @return Instance of the current animator
*/
inline Animator *switchColon() noexcept {
animator_.colon_ = !animator_.colon_;
animator_.refresh();
return &animator_;
};
/**
* @brief Fill the screen with 0s
* @return Instance of the current animator
*/
inline Animator *clearScreen() noexcept {
animator_.clear();
cache_ = "";
return refresh();
};
/**
* @brief Set the value of the Dot
* @param value Value of the dop
* @return Instance of the current animator
*/
inline Animator *setDp(uint8_t value) noexcept {
animator_.dp_ = value;
return refresh();
}
/**
* @brief Get the current brightness level of the display
* @return uint8_t Level of the display's brightness
*/
inline uint8_t getBrightness() const noexcept { return static_cast<uint8_t>(animator_.brightness_); }
/**
* @brief Get the current brightness level of the display in percent
* @return float Level of the diplay's brightness in float
*/
inline float getBrightnessPercent() const noexcept {
return Animator::control2Percent(animator_.brightness_);
}
/**
* @brief Immediately change the brightness of the display
* @param value Display's brightness value between 0 and 8
*/
void changeBrightness(uint8_t value) noexcept {
animator_.brightness_ = Animator::fetchControl(value);
refresh();
};
/**
* @brief Set the brightness level of the display.
* @note The display doesn't refresh immediately, the new brightness is
* applied after the first `display()` call
* @param value Display's brightness value between 0 and 8
*/
void setBrightness(uint8_t value) noexcept {
animator_.brightness_ = Animator::fetchControl(value);
};
/**
* @brief Set brightness level of the display in percentage
* @param percent Display's brightness value between 0 and 100 percent
* @note The brightness of the display in percent is not linearly interpolated
* @return Instance of the current animator
*/
inline Animator *setBrightnessPercent(float percent) noexcept {
animator_.brightness_ = Animator::fetchControlPercent(percent);
return &animator_;
}
/**
* @brief Immediately change the brightness of the display in percentage
* @param percent Display's brightness value between 0 and 100 percent
* @return Instance of the current animator
*/
inline Animator *changeBrightnessPercent(float percent) noexcept {
animator_.brightness_ = Animator::fetchControlPercent(percent);
return refresh();
}
/**
* @brief Set the number of digits when displaying float values
* @param count number of digit values for float
*/
inline void setFloatDigitCount(unsigned count) {
floatDecimal_ = count;
}
private:
template<typename T>
typename type_traits::enable_if<type_traits::is_string<T>::value, String>::type stringer(T value) {
return value;
}
template<typename T>
typename type_traits::enable_if<type_traits::is_integral<T>::value, String>::type stringer(T value) {
return String(value);
}
template<typename T>
typename type_traits::enable_if<type_traits::is_floating_point<T>::value, String>::type stringer(T value) {
return String(value, static_cast<unsigned>(floatDecimal_));
}
private:
Animator animator_;
String cache_ = "";
unsigned floatDecimal_ = TOTAL_DIGITS;
};
#endif //TM1637_TM1637_H
| 10,061
|
C++
|
.h
| 342
| 23.280702
| 111
| 0.608642
|
AKJ7/TM1637
| 31
| 10
| 3
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,152
|
DeviceTable.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/devices/DeviceTable.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/controllerState/devices/DeviceTable.h>
using namespace inet;
using namespace std;
using namespace openflow;
namespace SDN4CoRE {
Define_Module(DeviceTable);
bool DeviceTable::addNetworkDevice(Switch_Info* sw_info) {
bool updated = false;
string swMacAddr = sw_info->getMacAddress();
cModule* switchModule = getSwitch(swMacAddr);
if (!switchModule) {
switchModule = createSwitch(swMacAddr);
updated = true;
}
for (int i = 0; i < sw_info->getNumOfPorts(); i++) {
if (!getSwitchPort(swMacAddr, i, switchModule)) {
createSwitchPort(swMacAddr, i, switchModule);
updated = true;
}
}
return updated;
}
int DeviceTable::getDeviceCount() const{
return cachedSwitches.size();
}
int DeviceTable::getLinkCount() const{
return links.size()/2; // contains all links twice
}
bool DeviceTable::linkNetworkDevices(std::string& swMacFirst,
int portFirst, std::string& swMacSecond, int portSecond) {
bool updated = false;
SwitchPort first (swMacFirst, portFirst);
SwitchPort second (swMacSecond, portSecond);
if(links.find(first) != links.end() || links.find(second) != links.end()) {
updated = true;
}
links[first] = second;
links[second] = first;
return updated;
}
bool DeviceTable::isLinkedToNetworkDevice(std::string& swMac,
int port) {
return links.find(SwitchPort(swMac,port)) != links.end();
}
SwitchPort DeviceTable::getLinkedSwitchPort(std::string& swMac, int port) {
auto iter = links.find(SwitchPort(swMac,port));
if (iter != links.end()) {
return iter->second;
}
return SwitchPort();
}
vector<DeviceLink_t> DeviceTable::getDeviceLinksForSwitch(
std::string& swMac) {
vector<DeviceLink_t> knownLinks;
for (auto& link : links) {
if(link.first.switchId == swMac) {
DeviceLink_t deviceLink (link.first, link.second);
knownLinks.push_back(deviceLink);
}
}
return knownLinks;
}
bool DeviceTable::loadConfig(cXMLElement* configuration) {
Enter_Method
("loadConfig");
bool changed = false;
if (configuration) {
cXMLElement* deviceTableXML;
if (configuration->isName("deviceTable")) {
deviceTableXML = configuration;
} else {
deviceTableXML = configuration->getFirstChildWithTag(
"deviceTable");
}
if (deviceTableXML) {
cXMLElementList linksXML = deviceTableXML->getChildrenByTagName(
"deviceLink");
for (cXMLElement* linkXML : linksXML) {
if (const char * firstSwMac = linkXML->getAttribute(
"firstSwMac")) {
if (const char * firstSwPort = linkXML->getAttribute(
"firstSwPort")) {
if (const char * secondSwMac = linkXML->getAttribute(
"secondSwMac")) {
if (const char * secondSwPort =
linkXML->getAttribute("secondSwPort")) {
int firstPort = atoi(firstSwPort);
int secondPort = atoi(secondSwPort);
string firstMac = firstSwMac;
string secondMac = secondSwMac;
cModule* swModule = getOrCreateSwitch(firstSwMac);
getOrCreateSwitchPort(firstSwMac,firstPort,swModule);
swModule = getOrCreateSwitch(secondSwMac);
getOrCreateSwitchPort(secondSwMac,secondPort,swModule);
changed = true;
linkNetworkDevices(firstMac, firstPort, secondMac, secondPort);
}
}
}
}
}
}
}
return changed;
}
bool DeviceTable::loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) {
Enter_Method
("loadConfig");
bool changed = false;
if (configuration) {
cXMLElement* deviceTableXML;
if (configuration->isName("deviceTable")) {
deviceTableXML = configuration;
} else {
deviceTableXML = configuration->getFirstChildWithTag(
"deviceTable");
}
if (deviceTableXML) {
cXMLElementList linksXML = deviceTableXML->getChildrenByTagName(
"deviceLink");
for (cXMLElement* linkXML : linksXML) {
if (const char * firstSwMac = linkXML->getAttribute(
"firstSwMac")) {
if (const char * secondSwMac = linkXML->getAttribute(
"secondSwMac")) {
if (strcmp(firstSwMac, swMacAddr.c_str()) == 0
|| strcmp(secondSwMac, swMacAddr.c_str())
== 0) {
if (const char * firstSwPort =
linkXML->getAttribute("firstSwPort")) {
if (const char * secondSwPort =
linkXML->getAttribute("secondSwPort")) {
int firstPort = atoi(firstSwPort);
int secondPort = atoi(secondSwPort);
string firstMac = firstSwMac;
string secondMac = secondSwMac;
cModule* swModule = getOrCreateSwitch(firstSwMac);
getOrCreateSwitchPort(firstSwMac,firstPort,swModule);
swModule = getOrCreateSwitch(secondSwMac);
getOrCreateSwitchPort(secondSwMac,secondPort,swModule);
changed = true;
linkNetworkDevices(firstMac, firstPort, secondMac, secondPort);
}
}
}
}
}
}
}
}
return changed;
}
void DeviceTable::dumpConfigToStream(std::ostream& stream,
int indentTabs) {
Enter_Method
("dumpConfigToStream");
string indent = string(indentTabs, '\t');
stream << indent << "<deviceTable>" << endl;
vector<DeviceLink_t> links = getAllDeviceLinks();
for (auto link : links) {
stream << string(indentTabs + 2, '\t') << "<deviceLink ";
stream << "firstSwMac=\"" << link.first.switchId << "\" ";
stream << "firstSwPort=\"" << link.first.port << "\" ";
stream << "secondSwMac=\"" << link.second.switchId << "\" ";
stream << "secondSwPort=\"" << link.second.port << "\" ";
stream << "/>" << endl;
}
stream << indent << "</deviceTable>" << endl;
}
vector<DeviceLink_t> DeviceTable::getAllDeviceLinks() {
vector<DeviceLink_t> knownLinks;
auto linksCopy = links; // copied known links
for (auto link : linksCopy) {
DeviceLink_t deviceLink (link.first, link.second);
linksCopy.erase(link.second); // ignore other direction
knownLinks.push_back(deviceLink);
}
return knownLinks;
}
void DeviceTable::initialize() {
ControllerStateManagementBase::initialize();
WATCH_MAP(links);
WATCH_PTRMAP(cachedSwitches);
}
void DeviceTable::refreshDisplay() const {
char buf[50];
sprintf(buf, "Devices: %d\nLinks: %d", getDeviceCount(), getLinkCount());
getDisplayString().setTagArg("t", 0, buf);
}
} /*end namespace SDN4CoRE*/
| 8,495
|
C++
|
.cc
| 207
| 29.463768
| 99
| 0.56844
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,153
|
SRPTableManagement.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/srp/SRPTableManagement.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/controllerState/srp/SRPTableManagement.h>
//STD
#include <string>
#include <sstream>
#include <algorithm>
//inet
#include "inet/linklayer/common/MACAddress.h"
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
using namespace std;
using namespace openflow;
using namespace CoRE4INET;
namespace SDN4CoRE {
Define_Module(SRPTableManagement);
bool SRPTableManagement::registerTalker(Switch_Info* swinfo, int arrivalPort,
TalkerAdvertise* talkerAdvertise) {
Enter_Method ("registerTalker");
//check if we need to create a table for this switch.
SRPTable* srpTable = getOrCreateManagedState(swinfo->getMacAddress());
//check if this talker is already known
PortModule* module =
dynamic_cast<PortModule*>(srpTable->getTalkerForStreamId(
talkerAdvertise->getStreamID(),
talkerAdvertise->getVlan_identifier()));
if (module && module->getPort() != arrivalPort) {
//talker is already known to us but with a different port.
throw std::invalid_argument("Talker already exists on another port");
} else {
module = getOrCreateSwitchPort(swinfo->getMacAddress(), arrivalPort);
}
SR_CLASS srClass;
if (talkerAdvertise->getPriorityAndRank() == PRIOANDRANK_SRCLASSA) {
srClass = SR_CLASS::A;
} else if (talkerAdvertise->getPriorityAndRank() == PRIOANDRANK_SRCLASSB) {
srClass = SR_CLASS::B;
} else {
srClass = SR_CLASS::A;
}
//only take first 3 bit and shift them to fit the uint8_t
uint8_t pcp = (talkerAdvertise->getPriorityAndRank() & 0xE0) >> 5;
return srpTable->updateTalkerWithStreamId(talkerAdvertise->getStreamID(),
module, talkerAdvertise->getDestination_address(), srClass,
talkerAdvertise->getMaxFrameSize(),
talkerAdvertise->getMaxIntervalFrames(),
talkerAdvertise->getVlan_identifier(), pcp, false);
}
bool SRPTableManagement::registerListener(openflow::Switch_Info* swinfo,
int arrivalPort, CoRE4INET::ListenerReady* listenerReady) {
Enter_Method ("registerListener");
//check if there is a table for this switch
SRPTable* srpTable = getManagedState(swinfo->getMacAddress());
if (!srpTable) {
return false;
}
//check if this listener is already known
PortModule* module = nullptr;
std::list<cModule*> listeners = srpTable->getListenersForStreamId(
listenerReady->getStreamID(), listenerReady->getVlan_identifier());
for (auto listener : listeners) {
PortModule* port = dynamic_cast<PortModule*>(listener);
if (port->getPort() == arrivalPort) {
module = port;
break;
}
}
if (!module) {
module = getOrCreateSwitchPort(swinfo->getMacAddress(), arrivalPort);
}
srpTable->updateListenerWithStreamId(listenerReady->getStreamID(), module,
listenerReady->getVlan_identifier());
return true;
}
int SRPTableManagement::getTalkerPort(openflow::Switch_Info* switchInfo, uint64_t streamId, uint16_t vid) {
Enter_Method("getTalkerPort");
SRPTable* srpTable = getManagedState(switchInfo->getMacAddress());
if (!srpTable) {
throw cRuntimeError("There is no srp table for this switch!");
}
if(PortModule* module = dynamic_cast<PortModule*>(srpTable->getTalkerForStreamId(streamId,vid))){
return module->getPort();
}
return -1;
}
SRPTableManagement::SRPForwardingInfo_t* SRPTableManagement::getForwardingInfoForStreamID(
Switch_Info* swinfo, uint64_t streamID, uint16_t vlan_id) {
Enter_Method ("getForwardingInfoForStreamID");
SRPForwardingInfo_t* fwd = new SRPForwardingInfo_t();
SRPTable* srpTable = getManagedState(swinfo->getMacAddress());
if (!srpTable) {
throw cRuntimeError(
"Forwarding info for switch requested, but there is no srp table for it.");
}
//gather all needed information
fwd->streamID = streamID;
fwd->vlanID = vlan_id;
//get talker
SRPTable::TalkerEntry* talker = srpTable->getTalkerEntryForStreamId(
streamID, vlan_id);
if (talker) {
fwd->srClass = (uint8_t) talker->srClass;
fwd->dest = talker->address;
fwd->inPort = dynamic_cast<PortModule*>(talker->module)->getPort();
fwd->pcp = talker->pcp;
} else {
throw cRuntimeError(
"Forwarding info for stream requested, but there is no talker entry in srp table.");
}
//get listerners
std::list<cModule*> listeners = srpTable->getListenersForStreamId(streamID,
vlan_id);
//fill the output info for each listener.
for (auto listener : listeners) {
PortModule* port = dynamic_cast<PortModule*>(listener);
if (std::find(fwd->outports.begin(), fwd->outports.end(),
port->getPort()) != fwd->outports.end()) {
//already outputting to this port
} else {
fwd->outports.push_back(port->getPort());
}
}
return fwd;
}
void SRPTableManagement::dumpConfigToStream(std::ostream& stream,
int indentTabs) {
Enter_Method_Silent ("dumpConfigToStream");
ostringstream oss;
stream << string(indentTabs, '\t') << "<srpManager>" << endl;
const map<string, SRPTable*>& managedStates = getAllManagedStates();
for (auto table : managedStates) {
stream << exportSRPTableToXML(table.second, table.first, indentTabs + 1);
}
stream << string(indentTabs, '\t') << "</srpManager>" << endl;
}
bool SRPTableManagement::loadConfig(cXMLElement* configuration) {
Enter_Method_Silent ("loadConfig");
bool changed = false;
if (cXMLElement* srpManagerXML = locateSrpManagerInXML(configuration)) {
for (cXMLElement* table : srpManagerXML->getChildrenByTagName("srpTable")) {
if (const char* swMac = table->getAttribute("switch_id")) {
changed |= readSRPTableFromXML(table, swMac);
}
}
}
return changed;
}
bool SRPTableManagement::loadConfigForSwitch(const string& swMacAddr,
cXMLElement* configuration) {
Enter_Method_Silent ("loadConfigForSwitch");
if (cXMLElement* srpManagerXML = locateSrpManagerInXML(configuration)) {
for (cXMLElement* table : srpManagerXML->getChildrenByTagName("srpTable")) {
if (const char* swMac = table->getAttribute("switch_id")) {
if (strcmp(swMac, swMacAddr.c_str()) == 0) {
return readSRPTableFromXML(table, swMac);
}
}
}
}
return false;
}
void SRPTableManagement::onCreateManagedState(SRPTable* managedState,
std::string& swMacAddr) {
ControllerStateManagementBase<SRPTable>::onCreateManagedState(managedState,
swMacAddr);
managedState->par("agingTime").setDoubleValue(
this->par("agingTime").doubleValue());
}
cXMLElement* SRPTableManagement::locateSrpManagerInXML(cXMLElement* configuration) {
if (!configuration) {
return nullptr;
}
if (configuration->isName("srpManager")) {
return configuration;
} else {
return configuration->getFirstChildWithTag("srpManager");
}
}
bool SRPTableManagement::readSRPTableFromXML(cXMLElement* srp, const string& swMac) {
bool changed = false;
SRPTable* srpTable = getOrCreateManagedState(swMac);
if(cXMLElement* talkerTable = srp->getFirstChildWithTag("talkerTable")) {
for(auto talkerEntry : talkerTable->getChildrenByTagName("talkerEntry")){
if(const char* value = talkerEntry->getAttribute("vlan_id")){
uint16_t vlan_id = atoi(value);
if(const char* value = talkerEntry->getAttribute("stream_id")){
uint64_t stream_id = atoi(value);
if(const char* value = talkerEntry->getAttribute("srClass")){
SR_CLASS srClass = SR_CLASS::A;
if (!strcmp(value, "B")){
srClass = SR_CLASS::B;
}
if(const char* value = talkerEntry->getAttribute("address")){
inet::MACAddress address = inet::MACAddress(value);
if(const char* value = talkerEntry->getAttribute("framesize")){
size_t framesize = atoi(value);
if(const char* value = talkerEntry->getAttribute("intervalFrames")){
uint16_t intervalFrames = atoi(value);
if(const char* value = talkerEntry->getAttribute("pcp")){
uint8_t pcp = atoi(value);
if(const char* value = talkerEntry->getAttribute("port")){
int port = atoi(value);
PortModule* module = getOrCreateSwitchPort(swMac, port);
//all values are set correctly --> insert talker.
changed |= srpTable->updateTalkerWithStreamId(stream_id, module, address, srClass, framesize, intervalFrames, vlan_id, pcp, true);
}
}
}
}
}
}
}
}
}
}
if(cXMLElement* listenerTable = srp->getFirstChildWithTag("listenerTable")){
for(auto listenerEntry : listenerTable->getChildrenByTagName("listenerEntry")){
if(const char* value = listenerEntry->getAttribute("vlan_id")){
uint16_t vlan_id = atoi(value);
if(const char* value = listenerEntry->getAttribute("stream_id")){
uint64_t stream_id = atoi(value);
if(const char* value = listenerEntry->getAttribute("port")){
int port = atoi(value);
PortModule* module = getOrCreateSwitchPort(swMac, port);
//all values are set correctly --> insert listener.
changed |= srpTable->updateListenerWithStreamId(stream_id, module, vlan_id,true);
}
}
}
}
}
return changed;
}
string SRPTableManagement::exportSRPTableToXML (SRPTable* table, const string& swMac, int indentTabs) {
ostringstream oss;
oss << string(indentTabs, '\t') << "<srpTable switch_id=\""
<< swMac << "\" >" << endl;
oss << string(indentTabs+1, '\t') << "<talkerTable>" << endl;
for(auto& talkerEntry : table->getTalkerEntries()){
oss << string(indentTabs+2, '\t') << "<talkerEntry";
oss << " stream_id=\"" << talkerEntry.streamId << "\"";
oss << " vlan_id=\"" << talkerEntry.vlan_id << "\"";
oss << " srClass=\"" << SR_CLASStoString[talkerEntry.srClass] << "\"";
oss << " address=\"" << talkerEntry.address.str() << "\"";
oss << " port=\"" << dynamic_cast<PortModule*>(talkerEntry.module)->getPort() << "\"";
oss << " framesize=\"" << talkerEntry.framesize << "\"";
oss << " intervalFrames=\"" << talkerEntry.intervalFrames << "\"";
oss << " pcp=\"" << static_cast<int>(talkerEntry.pcp) << "\"";
oss << " />" << endl;
}
oss << string(indentTabs+1, '\t') << "</talkerTable>" << endl;
oss << string(indentTabs+1, '\t') << "<listenerTable>" << endl;
for(auto& listenerEntry : table->getListenerEntries()){
oss << string(indentTabs+2, '\t') << "<listenerEntry";
oss << " stream_id=\"" << listenerEntry.streamId << "\"";
oss << " vlan_id=\"" << listenerEntry.vlan_id << "\"";
oss << " port=\"" << dynamic_cast<PortModule*>(listenerEntry.module)->getPort() << "\"";
oss << " />" << endl;
}
oss << string(indentTabs+1, '\t') << "</listenerTable>" << endl;
oss << string(indentTabs, '\t') << "</srpTable>" << endl;
return oss.str();
}
} /*end namespace SDN4CoRE*/
| 12,881
|
C++
|
.cc
| 278
| 36.834532
| 174
| 0.614375
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,154
|
TopologyManagement.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/topology/TopologyManagement.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "sdn4core/controllerState/topology/TopologyManagement.h"
// INET
#include "inet/linklayer/ethernet/EtherFrame_m.h"
// CoRE4INET
#include "core4inet/utilities/customWatch.h"
using namespace std;
using namespace inet;
using namespace openflow;
//using namespace CoRE4INET;
namespace SDN4CoRE {
Define_Module(TopologyManagement);
TopologyManagement::TopologyManagement() {
}
TopologyManagement::~TopologyManagement() {
}
int TopologyManagement::findOutportAtSwitch(Switch_Info* swInfo,
OFP_Packet_In* packetIn) {
if (swInfo != nullptr && packetIn != nullptr) {
if (EthernetIIFrame* eth =
dynamic_cast<EthernetIIFrame *>(packetIn->getEncapsulatedPacket())) {
MACAddress hostMac = eth->getDest();
string switchId = swInfo->getMacAddress();
return findOutportAtSwitch(switchId, hostMac);
} else {
throw cRuntimeError("No Ethernet Frame found in PacketIn message.");
}
}
return -1;
}
int TopologyManagement::findOutportAtSwitch(string switchId,
MACAddress hostMac) {
if (hostMac.isBroadcast() || hostMac.isMulticast()
|| hostMac.isUnspecified()) {
return -1;
}
return findOutportAtSwitch(switchId,
hostTable->getHostForMacAddress(hostMac));
}
int TopologyManagement::findOutportAtSwitch(string switchId,
L3Address hostIp) {
if (hostIp.isBroadcast() || hostIp.isMulticast()
|| hostIp.isUnspecified()) {
return -1;
}
return findOutportAtSwitch(switchId, hostTable->getHostForIpAddress(hostIp));
}
int TopologyManagement::findOutportAtSwitch(string switchId,
HostTable::HostEntry* host) {
Enter_Method
("TopologyManagement::findOutportAtSwitch()");
if (host) {
int cachedHop = findNextHopInCache(switchId, host);
if (cachedHop != -1) {
return cachedHop;
}
Route route = findRoute(switchId, host);
if (!route.empty()) {
return route.front().port;
}
}
return -1;
}
SwitchPort TopologyManagement::findEdgePort(MACAddress hostMac) {
return findEdgePort(hostTable->getHostForMacAddress(hostMac));
}
SwitchPort TopologyManagement::findEdgePort(L3Address hostIp) {
return findEdgePort(hostTable->getHostForIpAddress(hostIp));
}
SwitchPort TopologyManagement::findEdgePort(HostTable::HostEntry* host) {
Enter_Method
("TopologyManagement::findEdgePort()");
if (host) {
// the hostTable already knows the edge port.
return SwitchPort(host->switch_id, host->portno);
}
return SwitchPort();
}
TopologyManagement::Route TopologyManagement::findRoute(string fromSwitch,
MACAddress hostMac) {
return findRoute(fromSwitch, hostTable->getHostForMacAddress(hostMac));
}
TopologyManagement::Route TopologyManagement::findRoute(string fromSwitch,
L3Address hostIp) {
return findRoute(fromSwitch, hostTable->getHostForIpAddress(hostIp));
}
TopologyManagement::Route TopologyManagement::findRoute(string fromSwitch,
HostTable::HostEntry* host) {
Route route;
if (host) {
route = calculateRoute(fromSwitch, host);
}
return route;
}
TopologyManagement::Route TopologyManagement::calculateRoute(string fromSwitch,
HostTable::HostEntry* host, string previousSwitch) {
// check if abort recursion!
if (host->switch_id == fromSwitch) {
cacheNextHop(fromSwitch, host, host->portno);
return Route( { SwitchPort(host->switch_id, host->portno) });
}
// check if cached
int cachedPort = findNextHopInCache(fromSwitch, host);
if (cachedPort != -1) {
SwitchPort linked = deviceTable->getLinkedSwitchPort(fromSwitch,
cachedPort);
Route route = calculateRoute(linked.switchId, host, fromSwitch);
if (!route.empty()) {
route.push_front(SwitchPort(fromSwitch, cachedPort));
return route;
} else {
// cache must be wrong...
cacheInvalidateNextHop(fromSwitch, host);
}
}
// check all device links
vector<DeviceLink_t> links = deviceTable->getDeviceLinksForSwitch(
fromSwitch);
for (auto& link : links) {
if(link.second.switchId == previousSwitch) {
// prevent loops
continue;
}
Route route = calculateRoute(link.second.switchId, host, fromSwitch);
if (!route.empty()) {
cacheNextHop(fromSwitch, host, link.first.port);
route.push_front(SwitchPort(link.first.switchId, link.first.port));
return route;
}
}
return Route();
}
int TopologyManagement::findNextHopInCache(string switchId,
HostTable::HostEntry* host) {
auto iter = cachedHops.find(host->macAddress);
if (iter != cachedHops.end()) {
auto inner = iter->second.find(switchId);
if (inner != iter->second.end()) {
return inner->second;
}
}
return -1;
}
void TopologyManagement::cacheInvalidateNextHop(std::string switchId,
HostTable::HostEntry* host) {
auto iter = cachedHops.find(host->macAddress);
if (iter != cachedHops.end()) {
auto inner = iter->second.find(switchId);
if (inner != iter->second.end()) {
iter->second.erase(inner);
}
}
}
void TopologyManagement::cacheNextHop(string switchId,
HostTable::HostEntry* host, int port) {
auto iter = cachedHops.find(host->macAddress);
if (iter != cachedHops.end()) {
iter->second[switchId] = port;
} else {
cachedHops[host->macAddress] = { {switchId, port}};
}
}
void TopologyManagement::initialize() {
ControllerStateManagementBase::initialize();
hostTable = check_and_cast<HostTable*>(
getModuleByPath(par("hostTablePath").stringValue()));
deviceTable = check_and_cast<DeviceTable*>(
getModuleByPath(par("deviceTablePath").stringValue()));
WATCH_MAPMAP(cachedHops);
}
} /*end namespace SDN4CoRE*/
| 6,760
|
C++
|
.cc
| 186
| 30.446237
| 85
| 0.683969
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,155
|
PortModule.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/base/PortModule.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "PortModule.h"
namespace SDN4CoRE{
Define_Module(PortModule);
void PortModule::initialize() {
WATCH(_port);
}
int PortModule::getPort(){
return _port;
}
void PortModule::setPort(int port) {
_port = port;
}
}
| 910
|
C++
|
.cc
| 27
| 31.888889
| 78
| 0.753425
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,156
|
ControllerStateManagementBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/base/ControllerStateManagementBase.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "ControllerStateManagementBase.h"
namespace SDN4CoRE {
// static member initialization...
int ControllerStateManagementWithID::nextID = 0;
} // End namespace SDN4CoRE
| 870
|
C++
|
.cc
| 21
| 40.142857
| 71
| 0.770686
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,157
|
MACTableManagement.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/mac/MACTableManagement.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/controllerState/mac/MACTableManagement.h>
using namespace inet;
using namespace std;
using namespace openflow;
namespace SDN4CoRE {
Define_Module(FriendMACAddressTable);
Define_Module(MACTableManagement);
bool MACTableManagement::update(openflow::Switch_Info* sw_info,
inet::MACAddress source, uint32_t in_port, int vlan_id) {
Enter_Method
("update");
FriendMACAddressTable* lookupTable = getOrCreateManagedState(
sw_info->getMacAddress());
return lookupTable->updateTableWithAddress(in_port, source, vlan_id);
}
int MACTableManagement::lookup(openflow::Switch_Info* sw_info,
inet::MACAddress destination, int vlan_id) {
Enter_Method
("lookup");
if (FriendMACAddressTable* lookupTable = getManagedState(
sw_info->getMacAddress())) {
return lookupTable->getPortForAddress(destination, vlan_id);
}
return MAC_MANAGER_OUTPORT_FLOOD;
}
bool MACTableManagement::loadConfig(cXMLElement* configuration) {
Enter_Method
("loadConfig");
bool changed = false;
if (configuration) {
cXMLElement* macManagerXML;
if (configuration->isName("macManager")) {
macManagerXML = configuration;
} else {
macManagerXML = configuration->getFirstChildWithTag("macManager");
}
if (macManagerXML) {
cXMLElementList switchesXML = macManagerXML->getChildrenByTagName(
"mactable");
for (cXMLElement* switchXML : switchesXML) {
if (const char * swMacAddr = switchXML->getAttribute(
"switch_id")) {
cXMLElementList macTableXML =
switchXML->getChildrenByTagName("entry");
if (!macTableXML.empty()) {
for (size_t i = 0; i < macTableXML.size(); i++) {
MACAddress mac = MACAddress(
macTableXML[i]->getAttribute("mac"));
if (!mac.isUnspecified()) {
if (const char * portC =
macTableXML[i]->getAttribute("port")) {
int port = atoi(portC);
int vlanId = 0;
if (const char * vlanIdC =
macTableXML[i]->getAttribute(
"vlan_id")) {
vlanId = atoi(vlanIdC);
}
FriendMACAddressTable* lookupTable =
this->getOrCreateManagedState(
string(swMacAddr));
changed |=
lookupTable->updateTableWithAddress(
port, mac, vlanId);
}
}
}
}
}
}
}
}
return changed;
}
bool MACTableManagement::loadConfigForSwitch(const string& swMacAddr,
cXMLElement* configuration) {
Enter_Method
("loadConfig");
bool changed = false;
if (configuration) {
cXMLElement* macManagerXML;
if (configuration->isName("macManager")) {
macManagerXML = configuration;
} else {
macManagerXML = configuration->getFirstChildWithTag("macManager");
}
if (macManagerXML) {
cXMLElementList switchesXML = macManagerXML->getChildrenByTagName(
"mactable");
for (cXMLElement* switchXML : switchesXML) {
if (const char * swMac = switchXML->getAttribute("switch_id")) {
if (strcmp(swMac, swMacAddr.c_str()) == 0) {
cXMLElementList macTableXML =
switchXML->getChildrenByTagName("entry");
if (!macTableXML.empty()) {
for (size_t i = 0; i < macTableXML.size(); i++) {
MACAddress mac = MACAddress(
macTableXML[i]->getAttribute("mac"));
if (!mac.isUnspecified()) {
if (const char * portC =
macTableXML[i]->getAttribute(
"port")) {
int port = atoi(portC);
int vlanId = 0;
if (const char * vlanIdC =
macTableXML[i]->getAttribute(
"vlan_id")) {
vlanId = atoi(vlanIdC);
}
FriendMACAddressTable* lookupTable =
this->getOrCreateManagedState(
swMac);
changed |=
lookupTable->updateTableWithAddress(
port, mac, vlanId);
}
}
}
}
}
}
}
}
}
return changed;
}
void MACTableManagement::dumpConfigToStream(std::ostream& stream,
int indentTabs) {
Enter_Method
("dumpConfigToStream");
string indent = string(indentTabs, '\t');
stream << indent << "<macManager>" << endl;
const map<string, FriendMACAddressTable*>& managedStates =
getAllManagedStates();
for (auto managedTableEntry : managedStates) {
stream << string(indentTabs + 1, '\t') << "<mactable switch_id=\""
<< managedTableEntry.first << "\">" << endl;
FriendMACAddressTable* managedTable = managedTableEntry.second;
for (auto vlanTables : managedTable->vlanAddressTable) {
for (auto entry : *(vlanTables.second)) {
stream << string(indentTabs + 2, '\t') << "<entry ";
stream << "vlan_id=\"" << vlanTables.first << "\" ";
stream << "mac=\"" << entry.first.str() << "\" ";
stream << "port=\"" << entry.second.portno << "\" ";
stream << "/>" << endl;
}
}
stream << string(indentTabs + 1, '\t') << "</mactable>" << endl;
}
stream << indent << "</macManager>" << endl;
}
void MACTableManagement::onCreateManagedState(
FriendMACAddressTable* managedState, string& swMacAddr) {
ControllerStateManagementBase<FriendMACAddressTable>::onCreateManagedState(
managedState, swMacAddr);
managedState->setAgingTime(this->par("agingTime").doubleValue());
}
} /*end namespace SDN4CoRE*/
| 7,955
|
C++
|
.cc
| 174
| 28.954023
| 84
| 0.494015
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,158
|
HostTable.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/hosts/HostTable.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "sdn4core/controllerState/hosts/HostTable.h"
// INET
#include "inet/linklayer/ethernet/EtherFrame_m.h"
#include "inet/networklayer/contract/INetworkDatagram.h"
// CoRE4INET
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
#include <algorithm>
using namespace std;
using namespace inet;
using namespace openflow;
using namespace CoRE4INET;
namespace SDN4CoRE {
Define_Module(HostTable);
std::ostream& operator<<(std::ostream& os, const HostTable::HostEntry& entry) {
os << "{";
os << "nodeName=" << entry.nodeName;
os << ", macAddress=" << entry.macAddress;
os << ", vid={";
bool first = true;
for (auto & vid : entry.vids) {
if (first) {
first = false;
} else {
os << ", ";
}
os << vid;
}
os << "}";
os << ", ipAddresses={";
first = true;
for (auto & address : entry.ipAddresses) {
if (first) {
first = false;
} else {
os << ", ";
}
os << address.str();
}
os << "}";
os << ", switch_id=" << entry.switch_id; // todo add full swinfo as string?
os << ", portno=" << entry.portno;
os << ", learned=" << entry.learned;
os << ", insertionTime=" << entry.insertionTime;
os << ", lastUpdated=" << entry.lastUpdated;
os << "}";
return os;
}
HostTable::HostTable() {
}
HostTable::~HostTable() {
clearTable();
}
bool HostTable::loadConfig(cXMLElement* configuration) {
return loadConfigForSwitch("", configuration);
}
bool HostTable::loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) {
Enter_Method
("loadConfig");
bool changed = false;
if (configuration) {
cXMLElement* hostTableXML;
if (configuration->isName("hostTable")) {
hostTableXML = configuration;
} else {
hostTableXML = configuration->getFirstChildWithTag("hostTable");
}
if (hostTableXML) {
cXMLElementList hostsXML = hostTableXML->getChildrenByTagName(
"host");
for (cXMLElement* hostXML : hostsXML) {
if (const char * switch_id = hostXML->getAttribute(
"switch_id")) {
if (swMacAddr.empty()
|| strcmp(switch_id, swMacAddr.c_str()) == 0) {
if (const char * macAddress = hostXML->getAttribute(
"macAddress")) {
MACAddress mac = MACAddress(macAddress);
if (!mac.isUnspecified()) {
if (const char * portC = hostXML->getAttribute(
"port")) {
int port = atoi(portC);
HostEntry* entry = new HostEntry();
if (const char * nodeName =
hostXML->getAttribute("nodeName")) {
entry->nodeName = nodeName;
}
entry->macAddress = mac;
entry->switch_id = switch_id;
entry->portno = port;
const char * vlanIdsC =
hostXML->getAttribute("vids");
if (vlanIdsC == nullptr) {
vlanIdsC = hostXML->getAttribute(
"vlan_id");
}
if (vlanIdsC != nullptr) {
for (auto vid : cStringTokenizer(
vlanIdsC, ",").asIntVector()) {
entry->vids.push_back(
static_cast<unsigned int>(vid));
}
} else {
entry->vids.push_back(0);
}
const char * ipsC = hostXML->getAttribute(
"ipAddresses");
if (ipsC == nullptr) {
ipsC = hostXML->getAttribute(
"ipAddress");
}
if (ipsC != nullptr) {
for (auto ipC : cStringTokenizer(ipsC,
",").asVector()) {
L3Address ip = L3Address(
ipC.c_str());
if (!ip.isUnspecified()) {
entry->ipAddresses.push_back(
ip);
}
}
}
entry->learned = false;
changed |= addHost(entry);
}
}
}
}
}
}
}
}
return changed;
}
void HostTable::dumpConfigToStream(std::ostream& stream, int indentTabs) {
Enter_Method
("dumpConfigToStream");
string indent = string(indentTabs, '\t');
stream << indent << "<hostTable>" << endl;
for (auto host : hostsByMac) {
stream << string(indentTabs + 2, '\t') << "<host ";
stream << "nodeName=\"" << host.second->nodeName << "\" ";
stream << "macAddress=\"" << host.second->macAddress.str() << "\" ";
stream << "port=\"" << host.second->portno << "\" ";
stream << "vids=\"";
bool first = true;
for (auto vid : host.second->vids) {
if (!first) {
stream << ",";
} else {
first = false;
}
stream << vid;
}
stream << "\" ";
stream << "ipAddresses=\"";
first = true;
for (auto ip : host.second->ipAddresses) {
if (!first) {
stream << ",";
} else {
first = false;
}
stream << ip.str();
}
stream << "\" ";
stream << "/>" << endl;
}
stream << indent << "</hostTable>" << endl;
}
bool HostTable::update(OFP_Packet_In* packetIn, Switch_Info * swInfo) {
Enter_Method
("HostTable::update()");
bool newHost = false;
if (EthernetIIFrame* eth =
dynamic_cast<EthernetIIFrame *>(packetIn->getEncapsulatedPacket())) {
const MACAddress& src_mac = eth->getSrc();
HostEntry* host = getHostForMacAddress(src_mac, false);
newHost = (host == nullptr);
if (newHost) {
host = new HostEntry();
host->learned = true;
host->macAddress = src_mac;
const string& switch_id = swInfo->getMacAddress();
host->switch_id = switch_id;
host->portno =
packetIn->getEncapsulatedPacket()->getArrivalGate()->getIndex();
// insert new host to table
hostsByMac[src_mac] = host;
if (hostsBySwitch.find(switch_id) == hostsBySwitch.end()) {
hostsBySwitch[switch_id] = HostList();
}
hostsBySwitch[switch_id].push_back(host);
}
unsigned int vid = 0;
if (EthernetIIFrameWithQTag* qframe =
dynamic_cast<EthernetIIFrameWithQTag *>(eth)) {
vid = qframe->getVID();
}
if (find(host->vids.begin(), host->vids.end(), vid)
== host->vids.end()) {
host->vids.push_back(vid);
}
if (eth->hasEncapsulatedPacket()) {
if (INetworkDatagram* ip = dynamic_cast<INetworkDatagram *>(eth->getEncapsulatedPacket())) {
const L3Address& src_ip = ip->getSourceAddress();
if (find(host->ipAddresses.begin(), host->ipAddresses.end(),
src_ip) == host->ipAddresses.end()) {
host->ipAddresses.push_back(src_ip);
hostsByIp[src_ip] = host;
}
}
//TODO Check what happens with ARP here.
}
host->lastUpdated = simTime();
} else {
throw cRuntimeError(
"Received Packet_In does not contain an Ethernet Frame.");
}
return !newHost;
}
bool HostTable::update(Switch_Info* swInfo, MACAddress source, uint32_t in_port,
int vlan_id) {
Enter_Method
("HostTable::update()");
HostEntry* host = getHostForMacAddress(source, false);
const string& switch_id = swInfo->getMacAddress();
bool newHost = (host == nullptr);
if (newHost) {
// we assume the first detection of the host mac as the entry point into the network.
host = new HostEntry();
host->learned = true;
host->macAddress = source;
host->portno = in_port;
host->switch_id = switch_id;
hostsByMac[source] = host;
if (hostsBySwitch.find(switch_id) == hostsBySwitch.end()) {
hostsBySwitch[switch_id] = HostList();
}
hostsBySwitch[switch_id].push_back(host);
}
if (find(host->vids.begin(), host->vids.end(), vlan_id)
!= host->vids.end()) {
host->vids.push_back(vlan_id);
}
host->lastUpdated = simTime();
return !newHost;
}
HostTable::HostEntry* HostTable::getHostForMacAddress(const MACAddress& address,
bool doAging) {
Enter_Method
("HostTable::getHostsForMacAddress()");
auto iter = hostsByMac.find(address);
if (iter == hostsByMac.end()) {
// not found
return nullptr;
}
if (doAging && isAgedHost(iter->second)) {
removeHost(iter->second);
return nullptr;
}
return iter->second;
}
HostTable::HostEntry* HostTable::getHostForIpAddress(const L3Address& address,
bool doAging) {
Enter_Method
("HostTable::getHostsForIPAddress()");
auto iter = hostsByIp.find(address);
if (iter == hostsByIp.end()) {
// not found
return nullptr;
}
if (doAging && isAgedHost(iter->second)) {
removeHost(iter->second);
return nullptr;
}
return iter->second;
}
HostTable::HostList HostTable::getHostsForSwitch(const string& switch_id,
bool doAging) {
Enter_Method
("HostTable::getHostsForSwitch()");
auto iter = hostsBySwitch.find(switch_id);
if (iter == hostsBySwitch.end()) {
// not found
return HostList();
}
if (doAging) {
for (auto innerIt = iter->second.begin(); innerIt != iter->second.end();
) {
auto curr = innerIt++;
if (isAgedHost(*curr)) {
removeHost(*curr);
}
}
}
return iter->second;
}
int HostTable::getHostCount() const {
return hostsByMac.size();
}
void HostTable::removeAgedEntries() {
for (auto iter = hostsByMac.begin(); iter != hostsByMac.end(); iter++) {
if (isAgedHost(iter->second)) {
removeHost(iter->second);
}
}
}
void HostTable::removeAgedEntriesIfNeeded() {
simtime_t now = simTime();
if (now >= lastPurge + 1) {
removeAgedEntries();
}
lastPurge = now;
}
void HostTable::clearTable() {
for (auto iter = hostsByMac.begin(); iter != hostsByMac.end(); iter++) {
delete iter->second;
}
hostsByMac.clear();
hostsByIp.clear();
hostsBySwitch.clear();
}
void HostTable::setAgingTime(simtime_t agingTime) {
this->agingTime = agingTime;
}
void HostTable::resetDefaultAging() {
agingTime = par("agingTime");
}
void HostTable::initialize() {
agingTime = par("agingTime");
lastPurge = SIMTIME_ZERO;
WATCH_PTRMAP(hostsByMac);
}
void HostTable::handleMessage(cMessage* msg) {
throw cRuntimeError("This module doesn't process messages");
}
void HostTable::refreshDisplay() const {
char buf[50];
sprintf(buf, "Hosts: %d", getHostCount());
getDisplayString().setTagArg("t", 0, buf);
}
bool HostTable::addHost(HostEntry* entry) {
if (!entry) {
return false;
}
auto hostIt = hostsByMac.find(entry->macAddress);
if (hostIt == hostsByMac.end()) {
// entry does not exist save pointer in hostTable and lookup tables
hostsByMac[entry->macAddress] = entry;
if (hostsBySwitch.find(entry->switch_id) == hostsBySwitch.end()) {
hostsBySwitch[entry->switch_id] = HostList();
}
hostsBySwitch[entry->switch_id].push_back(entry);
for (auto ipAddress : entry->ipAddresses) {
hostsByIp[ipAddress] = entry;
}
return true;
}
// entry already exist update ipAddresses and vlanIDs
// TODO is it safe to assume that the MAC, name, switch id + port are always known on host creation?
bool changed = false;
HostEntry* old = hostIt->second;
for (auto ipAddress : entry->ipAddresses) {
auto ipIt = find(old->ipAddresses.begin(), old->ipAddresses.end(),
ipAddress);
if (ipIt == old->ipAddresses.end()) {
old->ipAddresses.push_back(ipAddress);
hostsByIp[ipAddress] = old;
changed = true;
}
}
for (auto vid : entry->vids) {
auto vidIt = find(old->vids.begin(), old->vids.end(), vid);
if (vidIt == old->vids.end()) {
old->vids.push_back(vid);
changed = true;
}
}
if (!entry->learned && !entry->learned) {
// offline configuration for a host we already learned
old->learned = entry->learned;
changed = true;
}
old->lastUpdated = simTime();
if (old != entry) {
delete entry;
}
return changed;
}
bool HostTable::removeHost(HostEntry* entry) {
if (!entry) {
return false;
}
auto hostIt = hostsByMac.find(entry->macAddress);
if (hostIt == hostsByMac.end()) {
delete entry;
return false;
} else {
hostsByMac.erase(hostIt);
}
for (auto l3Addr : entry->ipAddresses) {
auto ipIt = hostsByIp.find(l3Addr);
if (ipIt != hostsByIp.end())
hostsByIp.erase(ipIt);
}
auto switchIt = hostsBySwitch.find(entry->switch_id);
if (switchIt != hostsBySwitch.end()) {
auto switchHostIt = find(switchIt->second.begin(),
switchIt->second.end(), entry);
if (switchHostIt != switchIt->second.end())
switchIt->second.erase(switchHostIt);
}
delete entry;
return true;
}
bool HostTable::isAgedHost(HostEntry* entry) {
return entry->learned && agingTime>0 && entry->lastUpdated + agingTime <= simTime();
}
} /*end namespace SDN4CoRE*/
| 15,959
|
C++
|
.cc
| 436
| 25.405963
| 104
| 0.520075
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,159
|
NetConfConfigMultipart.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/multipart/NetConfConfigMultipart.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastructures/multipart/NetConfConfigMultipart.h>
namespace SDN4CoRE {
NetConfConfigMultipart::NetConfConfigMultipart (const NetConfConfigMultipart &old_obj):NetConfConfig(old_obj) {
for( auto old_config: old_obj._configs){
NetConfConfig* newConfig = dynamic_cast<NetConfConfig*>(old_config->dup());
take(newConfig); // take ownership
this->_configs.push_back(newConfig);
}
}
SDN4CoRE::NetConfConfigMultipart::~NetConfConfigMultipart() {
for( auto config: _configs){
drop(config); // release ownership
if(config != nullptr){
delete config;
}
}
}
unsigned int NetConfConfigMultipart::getByteSize() {
unsigned int size = 0;
for(auto config: _configs){
size += config->getByteSize();
}
return size;
}
NetConfConfig_Base* NetConfConfigMultipart::dup() const {
return new NetConfConfigMultipart(*this);
}
std::vector<NetConfConfig*> NetConfConfigMultipart::getConfigurations() {
return _configs;
}
void NetConfConfigMultipart::setConfigurations(std::vector<NetConfConfig*> new_configs) {
//remove old configs
for( auto config: _configs){
drop(config); // release ownership
if(config != nullptr){
delete config;
}
}
_configs.clear();
//copy new ones
for( auto config: new_configs){
NetConfConfig* newConfig = dynamic_cast<NetConfConfig*>(config->dup());
take(newConfig); // take ownership
this->_configs.push_back(newConfig);
}
}
void NetConfConfigMultipart::addConfiguration(NetConfConfig* new_config) {
take(new_config); // take ownership
_configs.push_back(new_config);
}
} /* namespace SDN4CoRE */
| 2,444
|
C++
|
.cc
| 67
| 32.402985
| 111
| 0.715251
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,160
|
NetConfConfigCommitTimestamp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/transactionModel/NetConfConfigCommitTimestamp.cc
|
//
// c Mohammad Fazel Soltani, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastructures/transactionModel/NetConfConfigCommitTimestamp.h>
namespace SDN4CoRE {
NetConfConfigCommitTimestamp::NetConfConfigCommitTimestamp(){
}
NetConfConfigCommitTimestamp::~NetConfConfigCommitTimestamp(){
}
unsigned int NetConfConfigCommitTimestamp::getByteSize() {
return 108;//<config><top xmlns="http://example.com/schema/1.2/config"><cycle>32</cycle><period>0</period></top></config>
}
NetConfConfigCommitTimestamp::CommitTimestamp_t& NetConfConfigCommitTimestamp::getCommitTimestamp(){
return _timestamp;
}
void NetConfConfigCommitTimestamp::setCommitTimestamp(CommitTimestamp_t& commitTimestamp){
_timestamp = commitTimestamp;
}
} /* namespace SDN4CoRE */
| 1,452
|
C++
|
.cc
| 32
| 43.6875
| 125
| 0.795035
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,161
|
NetConfConfigIEEE8021Qbv.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/ieee8021qbv/NetConfConfigIEEE8021Qbv.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastructures/ieee8021qbv/NetConfConfigIEEE8021Qbv.h>
namespace SDN4CoRE {
NetConfConfigIEEE8021Qbv::NetConfConfigIEEE8021Qbv() {
}
NetConfConfigIEEE8021Qbv::~NetConfConfigIEEE8021Qbv() {
}
unsigned int NetConfConfigIEEE8021Qbv::getByteSize() {
return _gateConfigurations.size() * sizeof(IEEE8021QbvGateConfig_t);
}
NetConfConfigIEEE8021Qbv::IEEE8021QbvGateConfig_t* NetConfConfigIEEE8021Qbv::getGateConfigurationForPort(
int port) {
for(IEEE8021QbvGateConfig_t* gateConfig: _gateConfigurations){
if(gateConfig->port == port) {
return gateConfig;
}
}
return nullptr;
}
void NetConfConfigIEEE8021Qbv::setGateConfiguration(IEEE8021QbvGateConfig_t* config) {
for(auto gateConfig: _gateConfigurations){
if(gateConfig->port == config->port) {
gateConfig = config;
return;
}
}
_gateConfigurations.push_back(config);
}
} /* namespace SDN4CoRE */
| 1,690
|
C++
|
.cc
| 44
| 34.840909
| 105
| 0.751374
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,162
|
OF_NetConfConfigFlowMod.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/openflow/OF_NetConfConfigFlowMod.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastructures/openflow/OF_NetConfConfigFlowMod.h>
namespace SDN4CoRE {
OF_NetConfConfigFlowMod::OF_NetConfConfigFlowMod(){}
OF_NetConfConfigFlowMod::~OF_NetConfConfigFlowMod(){}
OF_NetConfConfigFlowMod::OF_NetConfConfigFlowMod(const OF_NetConfConfigFlowMod &old_obj){
this->flowTableConfigs = old_obj.flowTableConfigs;
}
void OF_NetConfConfigFlowMod::setFlowTableConfigs(std::vector<OF_FlowTableConfig_t*> flowTableConfigs){
this->flowTableConfigs = flowTableConfigs;
}
void OF_NetConfConfigFlowMod::addFlowTableConfig(OF_FlowTableConfig_t* flowTableConfig){
this->flowTableConfigs.push_back(flowTableConfig);
}
std::vector<OF_NetConfConfigFlowMod::OF_FlowTableConfig_t*> OF_NetConfConfigFlowMod::getFlowTableConfigs(){
return this->flowTableConfigs;
}
unsigned int OF_NetConfConfigFlowMod::getByteSize(){
return sizeof(OF_FlowTableConfig_t) * flowTableConfigs.size();
}
NetConfConfig_Base *OF_NetConfConfigFlowMod::dup()const {
return new OF_NetConfConfigFlowMod(*this);
}
}
| 1,749
|
C++
|
.cc
| 39
| 42.923077
| 107
| 0.798587
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,163
|
NetConfConfigSRP.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/srp/NetConfConfigSRP.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastructures/srp/NetConfConfigSRP.h>
namespace SDN4CoRE {
SDN4CoRE::NetConfConfigSRP::NetConfConfigSRP(const NetConfConfigSRP& old_obj) {
for( auto listener : old_obj._listeners){
CoRE4INET::SRPTable::ListenerEntry newListener = *dynamic_cast<CoRE4INET::SRPTable::ListenerEntry*>(listener.dup());
_listeners.push_back(newListener);
}
for( auto talker : old_obj._talkers){
CoRE4INET::SRPTable::TalkerEntry newTalker = *dynamic_cast<CoRE4INET::SRPTable::TalkerEntry*>(talker.dup());
_talkers.push_back(newTalker);
}
}
unsigned int SDN4CoRE::NetConfConfigSRP::getByteSize() {
return ( sizeof(CoRE4INET::SRPTable::TalkerEntry) * _talkers.size()) + ( sizeof(CoRE4INET::SRPTable::ListenerEntry) * _listeners.size());
}
NetConfConfig_Base* SDN4CoRE::NetConfConfigSRP::dup() const {
return new NetConfConfigSRP(*this);
}
void SDN4CoRE::NetConfConfigSRP::setTalkerEntries(
std::vector<CoRE4INET::SRPTable::TalkerEntry> talkers) {
_talkers = talkers;
}
void SDN4CoRE::NetConfConfigSRP::setListenerEntries(
std::vector<CoRE4INET::SRPTable::ListenerEntry> listeners) {
_listeners = listeners;
}
std::vector<CoRE4INET::SRPTable::TalkerEntry> SDN4CoRE::NetConfConfigSRP::getTalkerEntries() {
return _talkers;
}
std::vector<CoRE4INET::SRPTable::ListenerEntry> SDN4CoRE::NetConfConfigSRP::getListenerEntries() {
return _listeners;
}
void SDN4CoRE::NetConfConfigSRP::addTalkerEntry(
CoRE4INET::SRPTable::TalkerEntry talker) {
_talkers.push_back(talker);
}
void SDN4CoRE::NetConfConfigSRP::addListenerEntry(
CoRE4INET::SRPTable::ListenerEntry listener) {
_listeners.push_back(listener);
}
} /* namespace SDN4CoRE */
| 2,457
|
C++
|
.cc
| 57
| 39.982456
| 141
| 0.754085
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,164
|
NetConfConfig.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/base/NetConfConfig.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "sdn4core/netconf/datastructures/base/NetConfConfig.h"
namespace SDN4CoRE {
NetConfConfig::NetConfConfig() {}
NetConfConfig::~NetConfConfig() {}
unsigned int NetConfConfig::getByteSize() {
return 4;
}
} /* namespace SDN4CoRE */
| 957
|
C++
|
.cc
| 24
| 38.458333
| 78
| 0.76699
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,165
|
NetConfFilter.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/base/NetConfFilter.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "sdn4core/netconf/datastructures/base/NetConfFilter.h"
namespace SDN4CoRE {
NetConfFilter::NetConfFilter() {}
NetConfFilter::~NetConfFilter() {}
unsigned int NetConfFilter::getByteSize() {
return 4;
}
} /* namespace SDN4CoRE */
| 957
|
C++
|
.cc
| 24
| 38.458333
| 78
| 0.76699
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,166
|
NetConfRunningDataStore.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/store/running/NetConfRunningDataStore.cc
|
//
// c Tobias Haugg, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/datastores/store/running/NetConfRunningDataStore.h>
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
#include <sdn4core/netconf/datastores/config/multipart/NetConfDataConfiguratorMultipart.h>
#include <sdn4core/utility/dynamicmodules/DynamicModuleHandling.h>
using namespace std;
namespace SDN4CoRE {
Define_Module(NetConfRunningDataStore);
void NetConfRunningDataStore::initialize() {
NetConfDataStoreBase::initialize();
auto configurators = getParentModule()->getSubmodule("configurators", 0);
bool hasMultipart = false;
if(configurators) {
int numConfigurators = configurators->getVectorSize();
for (int i = 0; i < numConfigurators; i++) {
NetConfDataConfiguratorBase* configurator =
dynamic_cast<NetConfDataConfiguratorBase*>(getParentModule()->getSubmodule(
"configurators", i));
if (configurator) {
_configurators.push_back(configurator);
if(auto multiPartConfig = dynamic_cast<NetConfDataConfiguratorMultipart*>(configurator)){
hasMultipart = true;
}
}
}
}
if(!hasMultipart){
auto multipartModule = createDynamicModule(
"sdn4core.netconf.datastores.config.multipart.NetConfDataConfiguratorMultipart",
"configurators",
this->getParentModule(),
true);
if(auto multiPartConfig = dynamic_cast<NetConfDataConfiguratorMultipart*>(multipartModule)){
multiPartConfig->finalizeParameters();
_configurators.push_back(multiPartConfig);
} else {
throw cRuntimeError("Could not create multipart configurator module");
}
}
}
NetConfConfig *NetConfRunningDataStore::getConfig(const NetConfFilter& filter) {
Enter_Method("getConfig()");
for (auto configurator : _configurators) {
if (NetConfConfig* config = configurator->getConfig(filter)) {
return config;
}
}
return nullptr;
}
bool NetConfRunningDataStore::editConfig(int defaultOperation, int errorOption,
NetConfConfig* config) {
Enter_Method("editConfig()");
bool newConfigs = false;
for (auto configurator : _configurators) {
if (configurator->editConfig(defaultOperation, errorOption, config)) {
newConfigs = true;
}
}
if(newConfigs){
emit(editConfigOkSignal,1L);
}else{
emit(editConfigErrorSignal,1L);
}
return newConfigs;
}
bool NetConfRunningDataStore::validateConfig(NetConfConfig* config) {
Enter_Method("validateConfig()");
for (auto configurator : _configurators) {
if (configurator->validateConfig(config)) {
return true;
}
}
return false;
}
}
| 3,605
|
C++
|
.cc
| 91
| 33
| 105
| 0.694635
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,167
|
NetConfCandidateDataStore.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/store/candidate/NetConfCandidateDataStore.cc
|
//
// c Mohammad Fazel Soltani, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastores/store/candidate/NetConfCandidateDataStore.h>
namespace SDN4CoRE {
Define_Module(NetConfCandidateDataStore);
NetConfCandidateDataStore::~NetConfCandidateDataStore()
{
clear();
}
void NetConfCandidateDataStore::initialize(){
NetConfDataStoreBase::initialize();
_runningStore = dynamic_cast<NetConfRunningDataStore*>(this->getParentModule()->getSubmodule("running"));
if(!_runningStore) {
throw cRuntimeError("Could not find running store.");
}
}
NetConfConfig* NetConfCandidateDataStore::getConfig(const NetConfFilter& filter){
Enter_Method("getConfig()");
throw cRuntimeError("Not yet implemented");
return new NetConfConfig();
}
bool NetConfCandidateDataStore::editConfig(int defaultOperation, int errorOption, NetConfConfig* config){
Enter_Method("editConfig()");
bool newConfigs = false;
if(config){
if(validateConfig(config)){
if(auto dup = dynamic_cast<NetConfConfig*>(config->dup())) {
_configVector.push_back(dup);
newConfigs = true;
} else {
throw cRuntimeError("Duplication of config failed");
}
}
}
if(newConfigs){
emit(editConfigOkSignal, 1L);
}else{
emit(editConfigErrorSignal, 1L);
}
return newConfigs;
}
bool NetConfCandidateDataStore::validateConfig(NetConfConfig* config){
return _runningStore->validateConfig(config);
}
bool NetConfCandidateDataStore::checkAndLock(int lockHolderSessionId){
if(!_configVector.empty()){
return false;
}else{
return NetConfDataStoreBase::checkAndLock(lockHolderSessionId);
}
}
bool NetConfCandidateDataStore::applyTo(NetConfDataStoreBase* running){
Enter_Method("applyTo(%s)", running->getName());
bool success = true;
for(auto configChange: _configVector){
success = success && running->editConfig(NetConfOperation_Operation::NETCONFOPERATION_OPERATION_MERGE,
NetConfOperation_ErrorOption::NETCONFOPERATION_ERROROPTION_ROLLBACKONERROR,
configChange);
}
this->clear();
return success;
}
void NetConfCandidateDataStore::clear(){
Enter_Method("clear()");
for(auto config: _configVector){
delete config;
}
_configVector.clear();
}
} /* namespace SDN4CoRE */
| 3,092
|
C++
|
.cc
| 84
| 32.011905
| 110
| 0.721963
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,168
|
NetConfDataStoreBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/store/base/NetConfDataStoreBase.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "sdn4core/netconf/datastores/store/base/NetConfDataStoreBase.h"
namespace SDN4CoRE {
simsignal_t NetConfDataStoreBase::editConfigOkSignal = registerSignal("editConfigOk");
simsignal_t NetConfDataStoreBase::editConfigErrorSignal = registerSignal("editConfigError");
void NetConfDataStoreBase::initialize()
{
//Do nothing for now.
WATCH(this->lockHolderSessionId);
}
void NetConfDataStoreBase::handleMessage(cMessage *msg)
{
throw cRuntimeError("NetConfDataStoreBase does not handle messages...");
}
} /* namespace SDN4CoRE */
| 1,265
|
C++
|
.cc
| 30
| 40.433333
| 92
| 0.783564
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,169
|
NetConfDataStoreManagerBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/manager/base/NetConfDataStoreManagerBase.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/datastores/manager/base/NetConfDataStoreManagerBase.h>
#include <sdn4core/netconf/server/base/NetConfServerBase.h>
#include <sdn4core/utility/dynamicmodules/DynamicModuleHandling.h>
#include <sdn4core/netconf/messages/NetConfCtrlInfo_m.h>
#include <sdn4core/netconf/NetConfDefines.h>
// CORE4INET
#include "core4inet/scheduler/timer/Timer.h"
//INET
#include "inet/common/ModuleAccess.h"
using namespace std;
namespace SDN4CoRE {
Register_Class(NetConfDataStoreManagerBase);
const char NetConfDataStoreManagerBase::REQUEST_IN_GATE_NAME[] = "requestIn";
const char NetConfDataStoreManagerBase::RESPONSE_OUT_GATE_NAME[] = "responseIn";
simsignal_t NetConfDataStoreManagerBase::commitExecutionSignal = registerSignal("commitExecution");
simsignal_t NetConfDataStoreManagerBase::editConfigSignal = registerSignal("editConfig");
NetConfDataStoreManagerBase::~NetConfDataStoreManagerBase()
{
if (_commitOperation != nullptr)
{
delete _commitOperation;
}
}
void NetConfDataStoreManagerBase::initialize() {
handleParameterChange(nullptr);
//find netconf data stores
_netConfServer = inet::getModuleFromPar<NetConfServerBase>(
par("pathToNetConfServer"), this, true);
if (!_netConfServer) {
string msg = "No NetConf server found in ";
msg += par("pathToNetConfServer").stdstringValue();
throw cRuntimeError("%s",msg.c_str());
}
_runningStore = dynamic_cast<NetConfRunningDataStore*>(this->getParentModule()->getSubmodule("running"));
if (!_runningStore) {
throw cRuntimeError(
"No NetConf running config data store found ");
}
_candidateStore = dynamic_cast<NetConfCandidateDataStore*>(this->getParentModule()->getSubmodule("candidate"));
if (!_candidateStore) {
throw cRuntimeError(
"No NetConf candidate config data store found ");
}
// TODO implement XML startup configuration.
auto scheduler = this->getParentModule()->getParentModule()->getSubmodule("scheduler");
if(scheduler){
_newCycleSignal = registerSignal("newCycle");
int numOfPeriods = scheduler->getSubmodule("period", 0)->getVectorSize();
for(int i = 0; i < numOfPeriods; i++){
_periods.push_back(dynamic_cast<CoRE4INET::Period*>(scheduler->getSubmodule("period", i)));
}
}
resetCommitTimestamp();
WATCH(_commitTimestamp);
}
void NetConfDataStoreManagerBase::handleParameterChange(const char* parname) {
if (!parname || !strcmp(parname, "displayStatus")) {
_displayStatus = par("displayStatus");
}
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::createRPCReplyElement_Data(
NetConfConfig* config) {
NetConf_RPCReplyElement_Data* dataReply = nullptr;
if (config) {
dataReply = new NetConf_RPCReplyElement_Data();
dataReply->encapsulate(config);
dataReply->setByteLength(config->getByteSize());
}
return dynamic_cast<NetConf_RPCReplyElement*>(dataReply);
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::createRPCReplyElement_Error(
int error_type, const char * error_tag, int error_severity,
const char * error_app_tag = "") {
// create error
NetConf_RPCReplyElement_Error* errorReply =
new NetConf_RPCReplyElement_Error();
errorReply->setError_type(error_type);
errorReply->setError_tag(error_tag);
errorReply->setError_severity(error_severity);
errorReply->setError_app_tag(error_app_tag);
errorReply->addByteLength(std::strlen(error_tag) + std::strlen(error_app_tag));
return dynamic_cast<NetConf_RPCReplyElement*>(errorReply);
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::createRPCReplyElement_Ok() {
NetConf_RPCReplyElement_Ok* okReply = new NetConf_RPCReplyElement_Ok();
return dynamic_cast<NetConf_RPCReplyElement*>(okReply);
}
void NetConfDataStoreManagerBase::handleMessage(cMessage *msg) {
// the reply element to transmit after handling operation.
NetConf_RPCReplyElement* reply = nullptr;
if (NetConfOperation* operation = dynamic_cast<NetConfOperation*>(msg)) {
// check if it is of type get config operation
if (dynamic_cast<NetConfOperation_GetConfig*>(operation)) {
reply = handleGetConfig(operation);
}
// check if it is of type edit config operation
else if (dynamic_cast<NetConfOperation_EditConfig*>(operation)) {
reply = handleEditConfig(operation);
}
// check if it is of type copy config operation
else if (dynamic_cast<NetConfOperation_CopyConfig*>(operation)) {
reply = handleCopyConfig(operation);
}
// check if it is of type delete config operation
else if (dynamic_cast<NetConfOperation_DeleteConfig*>(operation)) {
reply = handleDeleteConfig(operation);
}
// check if it is of type get operation
else if (dynamic_cast<NetConfOperation_Get*>(operation)) {
reply = handleGet(operation);
}
// check if it is of type lock operation
else if (dynamic_cast<NetConfOperation_Lock*>(operation)){
reply = handleLock(operation);
}
// check if it is of type unlock operation
else if(dynamic_cast<NetConfOperation_Unlock*>(operation)){
reply = handleUnlock(operation);
}
// check if it is of type commit operation
else if(dynamic_cast<NetConfOperation_Commit*>(operation)){
reply = handleCommit(operation);
if(reply == nullptr) {
// this is a timed commit... so the reply is sent asynchronously
return;
}
}
// this operation is not known.
else {
// create error
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_RPC,
"This operation is not supported.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if (reply) {
// attach control info
reply->setControlInfo(operation->removeControlInfo());
// send the reply
sendDirect(reply, _netConfServer->gate(RESPONSE_OUT_GATE_NAME));
} else {
throw cRuntimeError(
"Received an operation that did not result in a reply, this should never happen!");
}
}
else if(msg->isSelfMessage() || dynamic_cast<CoRE4INET::SchedulerTimerEvent*>(msg)){
if(msg->isName("EXECUTE_TIMED_COMMIT")){
bool result = executeCommit();
if(_commitTimestamp.executeAtStartOfPeriod){
_periods[_commitTimestamp.period]->unsubscribe(_newCycleSignal, this);
}
if(result){
reply = createRPCReplyElement_Ok();
}
else{
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Commit Execution finished with errors",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
reply->setControlInfo(_commitOperation->removeControlInfo());
sendDirect(reply,_netConfServer->gate(RESPONSE_OUT_GATE_NAME));
resetCommitTimestamp();
}
}
else {
throw cRuntimeError("Received message the is not a netconf operation.");
}
delete msg;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleGetConfig(
NetConfOperation* operation) {
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type get config operation
if (NetConfOperation_GetConfig* getConfig =
dynamic_cast<NetConfOperation_GetConfig*>(operation)) {
NetConfConfig* config = nullptr;
if(strcmp(getConfig->getSource(), NETCONF_CONFIG_RUNNING) == 0) {
config = _runningStore->getConfig(getConfig->getFilter());
} else if (strcmp(getConfig->getSource(), NETCONF_CONFIG_CANDIDATE) == 0) {
config = _candidateStore->getConfig(getConfig->getFilter());
} else {
// create error
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"The Config store does not exist.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if (config) {
// create response
reply = createRPCReplyElement_Data(config);
} else {
// create error
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Failed to retrieve the data requested.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
return reply;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleEditConfig(
NetConfOperation* operation) {
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type edit config operation
if (NetConfOperation_EditConfig* editConfig =
dynamic_cast<NetConfOperation_EditConfig*>(operation)) {
bool success = false;
auto encap = editConfig->decapsulate();
NetConfDataStoreBase* storeToEdit = nullptr;
if(NetConfConfig* config = dynamic_cast<NetConfConfig*>(encap)){
if(strcmp(editConfig->getTarget(), NETCONF_CONFIG_RUNNING) == 0) {
storeToEdit = _runningStore;
} else if (strcmp(editConfig->getTarget(), NETCONF_CONFIG_CANDIDATE) == 0) {
storeToEdit = _candidateStore;
} else {
// create error
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"The Config store does not exist.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if (!verifyLock(storeToEdit, operation)) {
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Store Locked",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if(NetConfConfigCommitTimestamp* netconfCommitTimestamp = dynamic_cast<NetConfConfigCommitTimestamp*>(encap)){
NetConfConfigCommitTimestamp::CommitTimestamp_t commitTimestamp = netconfCommitTimestamp->getCommitTimestamp();
CoRE4INET::Timer* timer = dynamic_cast<CoRE4INET::Timer*>(this->getParentModule()->getParentModule()->getSubmodule("scheduler")->getSubmodule("timer"));
CoRE4INET::Period* period = _periods[commitTimestamp.period];
if((commitTimestamp.cycle > period->getCycles() && commitTimestamp.executeAtStartOfPeriod)
|| (commitTimestamp.time > timer->getTotalSimTime().dbl() && !commitTimestamp.executeAtStartOfPeriod)){
_commitTimestamp = netconfCommitTimestamp->getCommitTimestamp();
success = true;
}
else{
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Commit Timestamp is in the past.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
} else {
success = storeToEdit->editConfig(editConfig->getDefaultOperation(),
editConfig->getErrorOption(), config);
emit(editConfigSignal,1L);
}
} else {
throw cRuntimeError("Edit config does not contain a configuration");
}
delete encap;
if (success) {
// create response
reply = createRPCReplyElement_Ok();
} else {
// create error
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Failed to apply config.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
return reply;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleCopyConfig(
NetConfOperation* operation) {
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type copy config operation
if (NetConfOperation_CopyConfig* copyConfig =
dynamic_cast<NetConfOperation_CopyConfig*>(operation)) {
bool success = false;
if (!verifyLock(_runningStore, operation) || !verifyLock(_candidateStore, operation)) {
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Store Locked",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if( (strcmp(copyConfig->getSource(), NETCONF_CONFIG_CANDIDATE) == 0) &&
(strcmp(copyConfig->getTarget(), NETCONF_CONFIG_RUNNING) == 0) ) {
success = _candidateStore->applyTo(_runningStore);
if (success) {
// create response
reply = createRPCReplyElement_Ok();
} else {
// create error
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Failed to copy config.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
} else if ( (strcmp(copyConfig->getSource(), NETCONF_CONFIG_RUNNING) == 0) &&
(strcmp(copyConfig->getTarget(), NETCONF_CONFIG_CANDIDATE) == 0) ) {
_candidateStore->clear();
reply = createRPCReplyElement_Ok();
} else {
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Target or Source is unknown",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
return reply;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleDeleteConfig(
NetConfOperation* operation) {
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type delete config operation
if (NetConfOperation_DeleteConfig* deleteConfig =
dynamic_cast<NetConfOperation_DeleteConfig*>(operation)) {
if(strcmp(deleteConfig->getTarget(), NETCONF_CONFIG_RUNNING) == 0){
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"The running config must not be deleted.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
else if(strcmp(deleteConfig->getTarget(), NETCONF_CONFIG_CANDIDATE) == 0){
if (!verifyLock(_candidateStore, operation)) {
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Store Locked",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
_candidateStore->clear();
_candidateStore->unlock();
reply = createRPCReplyElement_Ok();
}
else{
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Target is unknown.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
return reply;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleGet(
NetConfOperation* operation) {
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type get operation
if (NetConfOperation_Get* get =
dynamic_cast<NetConfOperation_Get*>(operation)) {
NetConfConfig* config = new NetConfConfig();
if (config) {
// create response
reply = createRPCReplyElement_Data(config);
} else {
// create error
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Failed to retrieve the data requested.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
return reply;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleLock(
NetConfOperation* operation){
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type lock operation
if(NetConfOperation_Lock* lock =
dynamic_cast<NetConfOperation_Lock*>(operation)){
NetConfDataStoreBase* configStoreToLock = nullptr;
if(strcmp(lock->getTarget(), NETCONF_CONFIG_RUNNING) == 0) {
configStoreToLock = _runningStore;
} else if (strcmp(lock->getTarget(), NETCONF_CONFIG_CANDIDATE) == 0) {
configStoreToLock = _candidateStore;
} else {
// create error
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"The Config store does not exist.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if(NetConfCtrlInfo* controlInfo =
dynamic_cast<NetConfCtrlInfo*> (lock->getControlInfo())){
if(configStoreToLock->checkAndLock(controlInfo->getSession_id())){
reply = createRPCReplyElement_Ok();
}else{
auto owner = to_string(configStoreToLock->getLockOwner());
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"lock-denied",// error-tag is "lock-denied"
NETCONF_REPLY_ERROR_SEVIRITY_ERROR,
owner.c_str()//error-info is the session-id of the lock-owner, if the lock is held by a non-netconf entity it is 0
);
}
}
}
return reply;
}
bool NetConfDataStoreManagerBase::verifyLock(NetConfDataStoreBase* datastore, NetConfOperation* operation){
NetConfCtrlInfo* controlInfo = dynamic_cast<NetConfCtrlInfo*> (operation->getControlInfo());
int sessionId = controlInfo->getSession_id();
if(datastore->isLocked()){
if(!datastore->isLockedBy(sessionId)){
return false;
}
}
return true;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleUnlock(
NetConfOperation* operation){
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type unlock operation
if(NetConfOperation_Unlock* unlock =
dynamic_cast<NetConfOperation_Unlock*>(operation)){
NetConfDataStoreBase* configStoreToUnlock = nullptr;
if(strcmp(unlock->getTarget(), NETCONF_CONFIG_RUNNING) == 0) {
configStoreToUnlock = _runningStore;
} else if (strcmp(unlock->getTarget(), NETCONF_CONFIG_CANDIDATE) == 0) {
configStoreToUnlock = _candidateStore;
} else {
// create error
return createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"The Config store does not exist.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
if(NetConfCtrlInfo* controlInfo =
dynamic_cast<NetConfCtrlInfo*> (unlock->getControlInfo())){
if (!configStoreToUnlock->isLocked()) {
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"lock is not active", //error because lock is currently not active
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
else if(configStoreToUnlock->isLockedBy(controlInfo->getSession_id())){
configStoreToUnlock->unlock(); //success can be unlocked
reply = createRPCReplyElement_Ok();
}else{
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Cannot unlock config because session Id differs from lock owner", // locked but the current session is not the lock owner
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
}
return reply;
}
NetConf_RPCReplyElement* NetConfDataStoreManagerBase::handleCommit(
NetConfOperation* operation){
NetConf_RPCReplyElement* reply = nullptr;
// check if it is of type commit operation
if(NetConfOperation_Commit* commit =
dynamic_cast<NetConfOperation_Commit*>(operation)){
if(_runningStore != nullptr){
if (verifyLock(_runningStore, operation)) {
//valid commit
if(hasCommitTimestamp()){
scheduleTimedCommit(commit);
} else {
bool result = executeCommit();
if(result){
reply = createRPCReplyElement_Ok();
}
else{
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Commit Execution finished with errors",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
}
else{
reply = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Cannot commit because session Id differs from lock owner",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR);
}
}
}
return reply;
}
bool NetConfDataStoreManagerBase::hasCommitTimestamp(){
bool isCommitTimestamp = true;
if((_commitTimestamp.cycle == 0 && _commitTimestamp.executeAtStartOfPeriod)
|| (_commitTimestamp.time == 0 && !_commitTimestamp.executeAtStartOfPeriod)){
isCommitTimestamp = false;
}
return isCommitTimestamp;
}
void NetConfDataStoreManagerBase::scheduleTimedCommit(NetConfOperation_Commit* commit){
setCommitOperation(commit);
if(_commitTimestamp.executeAtStartOfPeriod){
//subscribe period cycles signal and wait for correct cycle to execute
_periods[_commitTimestamp.period]->subscribe(_newCycleSignal, this);
}else{
//
CoRE4INET::Timer* timer = dynamic_cast<CoRE4INET::Timer*>(this->getParentModule()->getParentModule()->getSubmodule("scheduler")->getSubmodule("timer"));
CoRE4INET::SchedulerTimerEvent* event = new CoRE4INET::SchedulerTimerEvent("EXECUTE_TIMED_COMMIT", CoRE4INET::TIMER_EVENT);
uint64_t ticksToCommitExecution = static_cast<uint64_t>(ceil((_commitTimestamp.time - timer->getTotalSimTime().dbl() ) / timer->getOscillator()->getPreciseTick()));
event->setTimer(ticksToCommitExecution);
event->setDestinationGate(gate("requestIn"));
timer->registerEvent(event);
}
}
bool NetConfDataStoreManagerBase::executeCommit(){
//apply config from candidate to running
emit(commitExecutionSignal,0L);
return _candidateStore->applyTo(_runningStore);
}
void NetConfDataStoreManagerBase::setCommitOperation(NetConfOperation_Commit* commitOperation){
if(_commitOperation != nullptr){
delete _commitOperation;
}
_commitOperation = commitOperation;
}
void NetConfDataStoreManagerBase::receiveSignal(cComponent *source, simsignal_t signalID, long l, cObject *details){
Enter_Method_Silent();
// check if signalID is equal to signal event
if(signalID == _newCycleSignal){
// check if source is the period on which is planned
if(dynamic_cast<CoRE4INET::Period*>(source) == _periods[_commitTimestamp.period]){
// check if the desired cycle has been reached
if(_periods[_commitTimestamp.period]->getCycles() == _commitTimestamp.cycle){
scheduleAt(simTime(), new cMessage("EXECUTE_TIMED_COMMIT"));
}
else if(_periods[_commitTimestamp.period]->getCycles() > _commitTimestamp.cycle){
throw cRuntimeError("The commit cycle timestamp was missed!");
}
//else wait until desired cycle is reached
}
}
}
void NetConfDataStoreManagerBase::resetCommitTimestamp(){
setCommitOperation(nullptr);
_commitTimestamp.cycle = 0;
_commitTimestamp.period = 0;
_commitTimestamp.time = 0;
_commitTimestamp.executeAtStartOfPeriod = false;
}
} // namespace SDN4CoRE
| 25,189
|
C++
|
.cc
| 550
| 34.987273
| 172
| 0.628483
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,170
|
NetConfDataConfiguratorMultipart.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/multipart/NetConfDataConfiguratorMultipart.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/multipart/NetConfDataConfiguratorMultipart.h>
#include <sdn4core/netconf/datastructures/multipart/NetConfConfigMultipart.h>
#include <sdn4core/netconf/messages/NetConfOperation_m.h>
namespace SDN4CoRE {
Define_Module(NetConfDataConfiguratorMultipart);
NetConfDataConfiguratorMultipart::~NetConfDataConfiguratorMultipart() {
}
void NetConfDataConfiguratorMultipart::initialize() {
auto running = getParentModule()->getSubmodule("running");
if (auto runningStore = dynamic_cast<NetConfRunningDataStore*>(running)){
this->_runningDataStore = runningStore;
} else {
throw cRuntimeError("Running data store not found");
}
}
NetConfConfig* SDN4CoRE::NetConfDataConfiguratorMultipart::getConfig(
const NetConfFilter& filter) {
throw cRuntimeError("Get Config not implemented");
}
bool SDN4CoRE::NetConfDataConfiguratorMultipart::editConfig(
int defaultOperation, int errorOption, NetConfConfig* config) {
Enter_Method("editConfig()");
bool status = true;
if(NetConfConfigMultipart* multiPartConfig = dynamic_cast<NetConfConfigMultipart*>(config)){
if((errorOption == NETCONFOPERATION_ERROROPTION_ROLLBACKONERROR) && !validateConfig(config)) {
return false;
}
for(auto config : multiPartConfig->getConfigurations()){
status &= _runningDataStore->editConfig(defaultOperation, errorOption, config);
if(!status && (errorOption == NETCONFOPERATION_ERROROPTION_STOPONERROR)){
return false;
}
}
} else {
return false;
}
//if no error or option was set NETCONFOPERATION_ERROROPTION_CONTINUEONERROR
return status;
}
bool SDN4CoRE::NetConfDataConfiguratorMultipart::validateConfig( NetConfConfig* config, int defaultOperationg) {
Enter_Method("validateConfig()");
NetConfConfigMultipart* multiPartConfig = dynamic_cast<NetConfConfigMultipart*>(config);
bool valid = multiPartConfig != nullptr;
if(valid){
for(auto config : multiPartConfig->getConfigurations()){
if(!_runningDataStore->validateConfig(config)){
valid = false;
break;
}
}
}
return valid;
}
} /* namespace SDN4CoRE */
| 3,019
|
C++
|
.cc
| 71
| 37.43662
| 112
| 0.73179
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,171
|
NetConfDataConfiguratorIEEE8021Qbv.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/ieee8021qbv/NetConfDataConfiguratorIEEE8021Qbv.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/ieee8021qbv/NetConfDataConfiguratorIEEE8021Qbv.h>
#include <sdn4core/netconf/datastructures/ieee8021qbv/NetConfConfigIEEE8021Qbv.h>
using namespace std;
using namespace CoRE4INET;
namespace SDN4CoRE {
Define_Module(NetConfDataConfiguratorIEEE8021Qbv);
void NetConfDataConfiguratorIEEE8021Qbv::initialize()
{
NetConfDataConfiguratorBase::initialize();
//find number of ports
int numPorts = getParentModule()->getParentModule()->getSubmodule(par("etherMacModule"),0)->getVectorSize();
//find IEEE8021QbvGateControlList modules of this device
for(int i=0; i<numPorts; i++){
cModule* module = getParentModule()->getParentModule()->getSubmodule(par("etherMacModule"),i)->getSubmodule("shaper")->getSubmodule("gateControlList");
if(module){
if(IEEE8021QbvGateControlList* gateControlListModule = dynamic_cast<IEEE8021QbvGateControlList*>(module)){
_gateControlListModules[i] = gateControlListModule;
} else {
cRuntimeError("Module found in \"^.etherMacModule.shaper.gateControlList\", but is no IEEE8021QbvGateControlList");
}
} else {
cRuntimeError("No Module found in \"^.etherMacModule.shaper.gateControlList\"");
}
}
}
NetConfConfig* NetConfDataConfiguratorIEEE8021Qbv::getConfig(
const NetConfFilter& filter) {
Enter_Method("getConfig()");
//todo add filter option
NetConfConfigIEEE8021Qbv* config = new NetConfConfigIEEE8021Qbv();
for (std::map<int, CoRE4INET::IEEE8021QbvGateControlList*>::iterator controlListIter =
_gateControlListModules.begin();
controlListIter != _gateControlListModules.end();
++controlListIter) {
NetConfConfigIEEE8021Qbv::IEEE8021QbvGateConfig_t gateConfig;
gateConfig.port = controlListIter->first;
gateConfig.gateControlList = controlListIter->second->par("controlList").stdstringValue();
}
return dynamic_cast<NetConfConfig*>(config);
}
bool NetConfDataConfiguratorIEEE8021Qbv::editConfig(int defaultOperation,
int errorOption, NetConfConfig* config) {
Enter_Method("editConfig()");
bool valid = validateConfig(config);
if(valid){
if(NetConfConfigIEEE8021Qbv* qbvConfig = dynamic_cast<NetConfConfigIEEE8021Qbv*>(config)){
for (std::map<int, CoRE4INET::IEEE8021QbvGateControlList*>::iterator controlListIter =
_gateControlListModules.begin();
controlListIter != _gateControlListModules.end();
++controlListIter) {
if(NetConfConfigIEEE8021Qbv::IEEE8021QbvGateConfig_t* gateConfig = qbvConfig->getGateConfigurationForPort(controlListIter->first)){
controlListIter->second->setGateControlList(gateConfig->gateControlList);
}
}
}
}
if(valid){
emit(editConfigOkSignal,1L);
}else{
emit(editConfigErrorSignal,1L);
}
return valid;
}
bool NetConfDataConfiguratorIEEE8021Qbv::validateConfig( NetConfConfig* config, int defaultOperationg) {
Enter_Method("validateConfig()");
NetConfConfigIEEE8021Qbv* qbvConfig = dynamic_cast<NetConfConfigIEEE8021Qbv*>(config);
bool valid = qbvConfig != nullptr;
if(valid){
for (auto gateConfig : qbvConfig->getGateConfigurations()) {
auto found = _gateControlListModules.find(gateConfig->port);
if(found == _gateControlListModules.end()) {
valid = false;
break;
}
}
}
return valid;
}
} /* namespace SDN4CoRE */
| 4,387
|
C++
|
.cc
| 96
| 38.875
| 159
| 0.709142
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,172
|
NetConfDataConfiguratorFlowTable.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/openflow/NetConfDataConfiguratorFlowTable.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//Openflow
#include "openflow/openflow/switch/flowtable/OF_FlowTableEntry.h"
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/openflow/NetConfDataConfiguratorFlowTable.h>
#include <sdn4core/netconf/datastructures/openflow/OF_NetConfConfigFlowMod.h>
using namespace openflow;
using namespace std;
namespace SDN4CoRE {
Define_Module(NetConfDataConfiguratorFlowTable);
void NetConfDataConfiguratorFlowTable::initialize(){
NetConfDataConfiguratorBase::initialize();
//load table modules.
int numFlowTables = getParentModule()->getParentModule()->getSubmodule("flowTables",0)->getVectorSize();
for (int i = 0; i < numFlowTables; i++) {
OF_FlowTable* table = dynamic_cast<OF_FlowTable*> (getParentModule()->getParentModule()->getSubmodule("flowTables",i));
if(table){
_flowTables.push_back(table);
}
}
}
NetConfConfig *NetConfDataConfiguratorFlowTable::getConfig(const NetConfFilter& filter){
OF_NetConfConfigFlowMod* config = new OF_NetConfConfigFlowMod();
for(int i = 0; i< _flowTables.size(); i++){
auto tableConfig = new OF_NetConfConfigFlowMod::OF_FlowTableConfig_t();
tableConfig->command = OF_NetConfConfigFlowMod::NO_ACTION;
tableConfig->table_id = i;
vector<OF_FlowTableEntry*> entries =_flowTables[i]->getEntrys();
for( auto entry : entries){
if(auto tmp = dynamic_cast<OF100_FlowTableEntry*>(entry)){
tableConfig->flowTableEntries.push_back(tmp);
}else{
throw cRuntimeError("NetConfConfigFlowMod: wrong flowEntry type, expected OF100_FlowTableEntry*");
}
}
config->addFlowTableConfig( tableConfig);
}
return (NetConfConfig*)config;
}
bool NetConfDataConfiguratorFlowTable::editConfig(int defaultOperation, int errorOption, NetConfConfig* config) {
Enter_Method("editConfig()");
bool status = false;
if(OF_NetConfConfigFlowMod* flowMod = dynamic_cast<OF_NetConfConfigFlowMod*>(config)){
for(auto flowTableConfig : flowMod->getFlowTableConfigs()){
for(OF100_FlowTableEntry* entry: flowTableConfig->flowTableEntries){
oxm_basic_match match = entry->getMatch();
auto priority = entry->getPriority();
switch(flowTableConfig->command){
case OF_NetConfConfigFlowMod::ADD_FLOW:
status = _flowTables[flowTableConfig->table_id]->addEntry(entry);
break;
case OF_NetConfConfigFlowMod::MODIFY_FLOW:
_flowTables[flowTableConfig->table_id]->deleteMatchingEntries(match, priority);
status = _flowTables[flowTableConfig->table_id]->addEntry(entry);
break;
case OF_NetConfConfigFlowMod::DELETE_FLOW:
_flowTables[flowTableConfig->table_id]->deleteMatchingEntries(match, priority);
status = true;
break;
default:
break;
}
}
}
}
if(status){
emit(editConfigOkSignal, 1L);
}else{
emit(editConfigErrorSignal, 1L);
}
return status;
}
bool NetConfDataConfiguratorFlowTable::validateConfig( NetConfConfig* config, int defaultOperationg) {
Enter_Method("validateConfig()");
bool status = false;
if(OF_NetConfConfigFlowMod* flowMod = dynamic_cast<OF_NetConfConfigFlowMod*>(config)){
for(auto flowTableConfig : flowMod->getFlowTableConfigs()){
for(int i=0; i < flowTableConfig->flowTableEntries.size(); i++){
switch(flowTableConfig->command){
case OF_NetConfConfigFlowMod::ADD_FLOW:
status = true;
break;
case OF_NetConfConfigFlowMod::MODIFY_FLOW:
status = true;
break;
case OF_NetConfConfigFlowMod::DELETE_FLOW:
status = true;
break;
default:
break;
}
}
}
}
return status;
}
}
| 4,950
|
C++
|
.cc
| 112
| 34.4375
| 127
| 0.641345
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,173
|
NetConfDataConfiguratorDummy.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/dummy/NetConfDataConfiguratorDummy.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastores/config/dummy/NetConfDataConfiguratorDummy.h>
namespace SDN4CoRE {
Define_Module(NetConfDataConfiguratorDummy);
NetConfConfig* NetConfDataConfiguratorDummy::getConfig(
const NetConfFilter& filter) {
Enter_Method("getConfig()");
return new NetConfConfig();
}
bool NetConfDataConfiguratorDummy::editConfig(int defaultOperation,
int errorOption, NetConfConfig* config) {
Enter_Method("editConfig()");
return true;
}
bool NetConfDataConfiguratorDummy::validateConfig( NetConfConfig* config, int defaultOperationg) {
Enter_Method("validateConfig()");
return true;
}
} /* namespace SDN4CoRE */
| 1,385
|
C++
|
.cc
| 34
| 38.235294
| 98
| 0.770833
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,174
|
NetConfDataConfiguratorSRP.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/srp/NetConfDataConfiguratorSRP.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/datastores/config/srp/NetConfDataConfiguratorSRP.h>
#include <sdn4core/netconf/datastructures/srp/NetConfConfigSRP.h>
#include <sdn4core/netconf/messages/NetConfOperation_m.h>
using namespace std;
namespace SDN4CoRE {
Define_Module(NetConfDataConfiguratorSRP);
void NetConfDataConfiguratorSRP::initialize() {
//load srp table module
_srpTable = dynamic_cast<CoRE4INET::SRPTable*> (getModuleByPath(par("ofSrpTableModule")));
if(!_srpTable){
throw cRuntimeError(("Could not init as no SRP Table could be found at " + par("srpTable").str()).c_str());
}
}
NetConfConfig* NetConfDataConfiguratorSRP::getConfig(const NetConfFilter& filter) {
NetConfConfigSRP* config = new NetConfConfigSRP();
config->setTalkerEntries(_srpTable->getTalkerEntries());
config->setListenerEntries(_srpTable->getListenerEntries());
return config;
}
bool NetConfDataConfiguratorSRP::editConfig(int defaultOperation, int errorOption, NetConfConfig* config) {
//check if config is valide and conforms the given operation
Enter_Method("editConfig()");
bool noError = true;
if(NetConfConfigSRP* configSRP = dynamic_cast<NetConfConfigSRP*>(config)){
if( (errorOption == NETCONFOPERATION_ERROROPTION_ROLLBACKONERROR) && !validateConfig(config, defaultOperation)){
return false;
}
for(auto talker : configSRP->getTalkerEntries()){
if(!noError && errorOption == NETCONFOPERATION_ERROROPTION_STOPONERROR){
return false;
}
switch(defaultOperation){
case NETCONFOPERATION_OPERATION_CREATE:
if(_srpTable->getTalkerForStreamId(talker.streamId, talker.vlan_id)){
noError = false;
}else{
_srpTable->updateTalkerWithStreamId(talker.streamId, talker.module, talker.address, talker.srClass, talker.framesize, talker.intervalFrames, talker.vlan_id, talker.pcp,true);
}
break;
case NETCONFOPERATION_OPERATION_MERGE:
_srpTable->updateTalkerWithStreamId(talker.streamId, talker.module, talker.address, talker.srClass, talker.framesize, talker.intervalFrames, talker.vlan_id, talker.pcp,true);
break;
case NETCONFOPERATION_OPERATION_DELETE:
noError &= _srpTable->removeTalkerWithStreamId(talker.streamId, talker.module, talker.address, talker.vlan_id);
break;
case NETCONFOPERATION_OPERATION_REMOVE:
_srpTable->removeTalkerWithStreamId(talker.streamId, talker.module, talker.address, talker.vlan_id);
break;
default:
break;
}
}
for(auto listener : configSRP->getListenerEntries()){
if(!noError && errorOption == NETCONFOPERATION_ERROROPTION_STOPONERROR){
return false;
}
switch(defaultOperation){
case NETCONFOPERATION_OPERATION_CREATE:
if((_srpTable->getListenersForStreamId(listener.streamId, listener.vlan_id).size()) <= 0){
noError = false;
}else{
_srpTable->updateListenerWithStreamId(listener.streamId, listener.module, listener.vlan_id);
}
break;
case NETCONFOPERATION_OPERATION_MERGE:
_srpTable->updateListenerWithStreamId(listener.streamId, listener.module, listener.vlan_id);
break;
case NETCONFOPERATION_OPERATION_DELETE:
noError &= _srpTable->removeListenerWithStreamId(listener.streamId, listener.module, listener.vlan_id);
break;
case NETCONFOPERATION_OPERATION_REMOVE:
_srpTable->removeListenerWithStreamId(listener.streamId, listener.module, listener.vlan_id);
break;
default:
break;
}
}
}else{
return false;
}
return noError;
}
bool NetConfDataConfiguratorSRP::validateConfig( NetConfConfig* config, int defaultOperation) {
if(NetConfConfigSRP* configSRP = dynamic_cast<NetConfConfigSRP*>(config)){
if( (defaultOperation == NETCONFOPERATION_OPERATION_CREATE) && (defaultOperation == NETCONFOPERATION_OPERATION_DELETE)){
for(auto listener : configSRP->getListenerEntries()){
if(!_srpTable->getListenersForStreamId(listener.streamId, listener.vlan_id).size()){
return false;
}
}
for(auto talker : configSRP->getTalkerEntries()){
if(!_srpTable->getTalkerEntryForStreamId(talker.streamId, talker.vlan_id)){
return false;
}
}
}
}else{
return false;
}
return true;
}
} /* namespace SDN4CoRE */
| 5,773
|
C++
|
.cc
| 119
| 37.663866
| 198
| 0.64448
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,175
|
NetConfDataConfiguratorBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "NetConfDataConfiguratorBase.h"
namespace SDN4CoRE{
simsignal_t NetConfDataConfiguratorBase::editConfigOkSignal = registerSignal("editConfigOk");
simsignal_t NetConfDataConfiguratorBase::editConfigErrorSignal = registerSignal("editConfigError");
}/* namespace SDN4CoRE */
| 995
|
C++
|
.cc
| 21
| 46.142857
| 99
| 0.790506
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,176
|
NetConfServerTCP.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/server/tcp/NetConfServerTCP.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/datastructures/tcp/NetConfServerSessionInfoTCP.h>
#include "NetConfServerTCP.h"
#include "sdn4core/netconf/messages/NetConfCtrlInfo_m.h"
using namespace inet;
namespace SDN4CoRE {
Define_Module(NetConfServerTCP);
void NetConfServerTCP::initialize() {
NetConfServerBase::initialize();
// TCP socket; listen on incoming connections
int port = par("localPort");
_serverSocket.setOutputGate(gate(TRANSPORT_OUT_GATE_NAME));
_serverSocket.setDataTransferMode(TCP_TRANSFER_OBJECT);
_serverSocket.bind(port);
_serverSocket.listen();
}
NetConfServerSessionInfo* NetConfServerTCP::openNewSession(cMessage* msg) {
NetConfServerSessionInfoTCP* sessionInfo = dynamic_cast<NetConfServerSessionInfoTCP*>(findSessionInfoForMsg(msg));
if(!sessionInfo){
// create the new socket from the message
TCPSocket *socket = new TCPSocket(msg);
socket->setOutputGate(gate(TRANSPORT_OUT_GATE_NAME ));
// create SessionInfo
sessionInfo = new NetConfServerSessionInfoTCP();
sessionInfo->setSessionId(_nextSessionId++);
sessionInfo->setSocket(socket);
sessionInfo->setConnId(socket->getConnectionId());
// insert into open sessions
_openSessions.push_back(sessionInfo);
}
return sessionInfo;
}
bool NetConfServerTCP::closeSession(int session_id) {
NetConfServerSessionInfoTCP* sessionInfo = dynamic_cast<NetConfServerSessionInfoTCP*>(findSessionInfoForId(session_id));
if(!sessionInfo){
// close socket
sessionInfo->getSocket()->close();
// delete from open sessions
for(auto i=_openSessions.begin(); i != _openSessions.end(); ++i) {
if((*i)->getSessionId() == sessionInfo->getSessionId()){
_openSessions.erase(i);
}
}
return true;
}
return false;
}
void NetConfServerTCP::sendToTransport(cMessage* msg) {
// Detach control info and use it for forwarding
NetConfCtrlInfo* ctrl = dynamic_cast<NetConfCtrlInfo*>(msg->removeControlInfo());
// get session info
NetConfServerSessionInfoTCP* sessionInfo = dynamic_cast<NetConfServerSessionInfoTCP*>(findSessionInfoForId(ctrl->getSession_id()));
// forward to tcp
sessionInfo->getSocket()->send(msg);
// delete control info
delete ctrl;
}
NetConfServerSessionInfo* NetConfServerTCP::findSessionInfoForMsg(cMessage* msg) {
TCPCommand *ind = dynamic_cast<TCPCommand *>(msg->getControlInfo());
if (!ind)
throw cRuntimeError("TCPSocketMap: findSocketFor(): no TCPCommand control info in message (not from TCP?)");
int connId = ind->getConnId();
for(auto i=_openSessions.begin(); i != _openSessions.end(); ++i) {
NetConfServerSessionInfoTCP* sessionInfo = dynamic_cast<NetConfServerSessionInfoTCP*>(*i);
if(sessionInfo->getConnId() == connId){
return sessionInfo;
}
}
return NULL;
}
} // namespace SDN4CoRE
| 3,702
|
C++
|
.cc
| 86
| 37.965116
| 135
| 0.721713
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,177
|
NetConfServerBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/server/base/NetConfServerBase.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/datastores/manager/base/NetConfDataStoreManagerBase.h>
#include <sdn4core/netconf/server/base/NetConfServerBase.h>
#include "sdn4core/netconf/messages/NetConfOperation_m.h"
#include "sdn4core/netconf/messages/NetConfCapability_m.h"
//INET
#include "inet/common/ModuleAccess.h"
//STD
#include <string>
using namespace std;
namespace SDN4CoRE {
const char NetConfServerBase::REQUEST_FWD_GATE_NAME[] = "requestIn";
const char NetConfServerBase::RESPONSE_IN_GATE_NAME[] = "responseIn";
const char NetConfServerBase::TRANSPORT_IN_GATE_NAME[] = "transportIn";
const char NetConfServerBase::TRANSPORT_OUT_GATE_NAME[] = "transportOut";
int NetConfServerBase::_nextSessionId = 0;
void NetConfServerBase::initialize() {
ProcessingTimeSimulation::initialize();
//find netconf data stores
_configDataStoreManager = inet::getModuleFromPar<NetConfDataStoreManagerBase>(
par("pathToConfigManager"), this, true);
if (!_configDataStoreManager) {
string msg = "No state data store found in ";
msg += par("pathToConfigManager").stdstringValue();
cRuntimeError("%s",msg.c_str());
}
}
NetConfMessage_RPCReply* NetConfServerBase::createRPCReply(
NetConf_RPCReplyElement* element) {
// if it is a reply detach NetConfCtrlInfo
NetConfCtrlInfo* ctrl =
dynamic_cast<NetConfCtrlInfo*>(element->removeControlInfo());
// create NetConf reply message
NetConfMessage_RPCReply* reply = new NetConfMessage_RPCReply("RPC Reply");
reply->setMessage_id(ctrl->getMessage_id());
reply->addByteLength(sizeof(ctrl->getMessage_id()));
reply->encapsulate(element);
// reattach control info and forward it.
reply->setControlInfo(ctrl);
return reply;
}
void NetConfServerBase::handleMessage(cMessage* msg) {
if (msg->arrivedOn(RESPONSE_IN_GATE_NAME)) {
// this should be a message from a data store --> check if it is NetConf_RPCReplyElement
NetConf_RPCReplyElement* element = dynamic_cast<NetConf_RPCReplyElement*>(msg);
if(element){
// if it is a reply detach NetConfCtrlInfo
NetConfMessage_RPCReply* reply = createRPCReply(element);
sendToTransport(reply);
} else {
delete msg;
}
} else {
//introduce processing delay
ProcessingTimeSimulation::handleMessage(msg);
}
}
void NetConfServerBase::processScheduledMessage(cMessage* msg) {
if (msg->arrivedOn(TRANSPORT_IN_GATE_NAME)) {
if (dynamic_cast<NetConfHello*>(msg)) {
// received hello
handleHello(msg);
} else if (NetConfMessage* netconf = dynamic_cast<NetConfMessage*>(msg)){
NetConfServerSessionInfo* sessionInfo = findSessionInfoForMsg(msg);
if(sessionInfo) {
// create control info
netconf->removeControlInfo();
netconf->setControlInfo(createCtrlInfoFor(sessionInfo,netconf));
//check for mesage type
switch(netconf->getMessageType()){
case NetConfMessageType::NETCONFMESSAGETYPE_RPC:
// received RPC
handleRPC(netconf);
break;
default:
NetConf_RPCReplyElement* element = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Incoming message not of type NETCONFMESSAGETYPE_RPC",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR,"");
element->setControlInfo(netconf->removeControlInfo());
NetConfMessage_RPCReply* reply = createRPCReply(element);
sendToTransport(reply);
break;
}
} else {
throw cRuntimeError("Received NetConfMessage but there is no session for it.");
}
}
}
delete msg;
}
void NetConfServerBase::handleHello(cMessage* msg) {
if (dynamic_cast<NetConfHello*>(msg)) {
// received hello so open a new session
NetConfServerSessionInfo* sessionInfo = openNewSession(msg);
// create hello
NetConfHello* reply = new NetConfHello("NetConfHello");
reply->setSession_id(sessionInfo->getSessionId());
//create and attach control info
NetConfCtrlInfo* info = new NetConfCtrlInfo();
info->setSession_id(sessionInfo->getSessionId());
reply->setControlInfo(info);
// send reply
sendToTransport(reply);
}
}
void NetConfServerBase::handleCloseSession(cMessage* msg) {
if(NetConfOperation* operation = dynamic_cast<NetConfOperation*>(msg)){
NetConfCtrlInfo* ctrl = dynamic_cast<NetConfCtrlInfo*>(operation->removeControlInfo());
NetConf_RPCReplyElement* element;
if(closeSession(ctrl->getSession_id())){
//session was closed
element = createRPCReplyElement_Ok();
} else {
//session could not be closed
element = createRPCReplyElement_Error(
NETCONF_REPLY_ERROR_TYPE_APPLICATION,
"Session could not be closed.",
NETCONF_REPLY_ERROR_SEVIRITY_ERROR,"");
}
// if it is a reply detach NetConfCtrlInfo
element->setControlInfo(ctrl);
NetConfMessage_RPCReply* reply = createRPCReply(element);
sendToTransport(reply);
}
}
NetConf_RPCReplyElement* NetConfServerBase::createRPCReplyElement_Error(
int error_type, const char * error_tag, int error_severity,
const char * error_app_tag = "") {
// create error
NetConf_RPCReplyElement_Error* errorReply =
new NetConf_RPCReplyElement_Error();
errorReply->setError_type(error_type);
errorReply->setError_tag(error_tag);
errorReply->setError_severity(error_severity);
errorReply->setError_app_tag(error_app_tag);
errorReply->addByteLength(std::strlen(error_tag) + std::strlen(error_app_tag));
return dynamic_cast<NetConf_RPCReplyElement*>(errorReply);
}
NetConf_RPCReplyElement* NetConfServerBase::createRPCReplyElement_Ok() {
NetConf_RPCReplyElement_Ok* okReply = new NetConf_RPCReplyElement_Ok();
return dynamic_cast<NetConf_RPCReplyElement*>(okReply);
}
void NetConfServerBase::handleRPC(NetConfMessage* msg) {
if(NetConfMessage_RPC* rpc = dynamic_cast<NetConfMessage_RPC*>(msg)){
// decapsulate the operation
if(NetConfOperation* operation = dynamic_cast<NetConfOperation*>(rpc->decapsulate())){
//get the control info
operation->setControlInfo(msg->removeControlInfo());
if(dynamic_cast<NetConfOperation_CloseSession*>(operation)){
handleCloseSession(operation);
}
//forward it to the config store manager
sendDirect(operation, _configDataStoreManager->gate(REQUEST_FWD_GATE_NAME));
}
}
}
NetConfServerSessionInfo* NetConfServerBase::findSessionInfoForId(
int sessionId) {
for(auto i=_openSessions.begin(); i != _openSessions.end(); ++i) {
if((*i)->getSessionId() == sessionId){
return (*i);
}
}
return NULL;
}
NetConfCtrlInfo* NetConfServerBase::createCtrlInfoFor(
NetConfServerSessionInfo* sessionInfo, NetConfMessage* msg) {
// create control info
NetConfCtrlInfo* ctrl = new NetConfCtrlInfo();
ctrl->setMessageType(msg->getMessageType());
ctrl->setSession_id(sessionInfo->getSessionId());
if(NetConfMessage_RPC* rpc = dynamic_cast<NetConfMessage_RPC*>(msg)){
ctrl->setMessage_id(rpc->getMessage_id());
} else if (NetConfMessage_RPCReply* rpc = dynamic_cast<NetConfMessage_RPCReply*>(msg)){
ctrl->setMessage_id(rpc->getMessage_id());
}
return ctrl;
}
} // namespace SDN4CoRE
| 8,669
|
C++
|
.cc
| 196
| 36.127551
| 96
| 0.671566
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,178
|
TransactionApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/transactionModel/TransactionApp.cc
|
//
// c Mohammad Fazel Soltani, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//CoRE4INET
#include "core4inet/scheduler/oscillator/Oscillator.h"
//SDN4CoRE
#include <sdn4core/netconf/applications/transactionModel/TransactionApp.h>
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserCollection.h>
#include <sdn4core/utility/xml/XMLUtility.h>
namespace SDN4CoRE{
Define_Module(TransactionApp);
void TransactionApp::initialize(){
LAMBDA_EVENT = new cMessage(SELFMESSAGE_LAMBDA);
controllerProcessingTime = this->par("controllerProcessingTime").doubleValue();
resultOfTransaction = registerSignal("transactionResult");
transactionDuration = registerSignal("transactionDuration");
enterNewPhase = registerSignal("enterNewPhase");
numSent = registerSignal("numSentMsgs");
numReceived = registerSignal("numReceivedMsgs");
WATCH(this->result);
WATCH(this->transactionState);
cXMLElement* xmlServerConnections = par("serverConnections").xmlValue();
if (xmlServerConnections) {
if (strcmp(xmlServerConnections->getName(), "server_connections")
== 0) {
cXMLElementList applicationsXML =
xmlServerConnections->getChildrenByTagName("application");
for (size_t i = 0; i < applicationsXML.size(); i++) {
std::string clientAppHost = getStringAttributeFromXML(applicationsXML[i],"client_host");
int clientAppIndex = getIntAttributeFromXML(applicationsXML[i],"client_app");
const char* realHost = getParentModule()->getParentModule()->getFullName();
if (clientAppIndex == getIndex() && (strcmp(realHost, clientAppHost.c_str()) == 0)) {
auto connectionList = NetConfAppConfigParserCollection::parseXMLConnectionList(
applicationsXML[i]->getChildrenByTagName("connection"), false);
double startHelloHandshake = this->par("startHelloHandshake").doubleValue();
for(auto connection : connectionList) {
connection.connectAt = startHelloHandshake;
_connections.push_back(connection);
}
}
}
}
}
WATCH_VECTOR(_connections);
scheduleNextConnection();
}
void TransactionApp::updatePhase(Phase newPhase){
emit(enterNewPhase,newPhase);
cDisplayString& parentDispStr = this->getDisplayString();
switch(newPhase){
case Phase::LOCK:
parentDispStr.setTagArg("i", 1, "#0066ff");
parentDispStr.setTagArg("t", 0, "Lock Phase");
break;
case Phase::CHANGE:
parentDispStr.setTagArg("i", 1, "#ff9933");
parentDispStr.setTagArg("t", 0, "Change Phase");
break;
case Phase::CONFIRMATION:
parentDispStr.setTagArg("i", 1, "#ffff00");
parentDispStr.setTagArg("t", 0, "Confirmation Phase");
break;
case Phase::UNLOCK:
parentDispStr.setTagArg("i", 1, "#ff0066");
parentDispStr.setTagArg("t", 0, "Confirmation Phase");
break;
case Phase::DEFAULT:
if(transactionState == TransactionAppState::EndOfTransaction){
parentDispStr.setTagArg("i", 1, "green");
parentDispStr.setTagArg("t", 0, "Success");
}else{
parentDispStr.setTagArg("i", 1, "red");
parentDispStr.setTagArg("t", 0, "Error");
}
break;
}
}
void TransactionApp::handleMessage(cMessage* msg){
if(isFSMAlphabet(msg)){
emit(numReceived, 1L);
finiteStateMachine(msg);
if(!isLambdaEvent(msg)){
delete msg;
}
} else{
NetConfApplicationBase::handleMessage(msg);
}
}
bool TransactionApp::scheduleNextConnection(){
bool result = false;
for (auto& connection : _connections) {
if(connection.state == ConnectionState_t::ConnectionStateWaiting) {
connection.state = ConnectionState_t::ConnectionStateScheduled;
cMessage* msg = new cMessage(SELFMESSAGE_SEND_HELLO);
msg->setContextPointer(&connection);
scheduleAt(connection.connectAt, msg);
result = true;
break;
}
}
return result;
}
bool TransactionApp::scheduleNextConfigurationFor(Connection_t* connection){
bool result = !_connections.empty();
for(auto& connection: _connections){
if(connection.state != ConnectionState_t::ConnectionStateEstablished){
result = false;
break;
}
}
if(result){
scheduleTransactionStart(this->par("startTransaction").doubleValue() + this->par("configStartOffset").doubleValue());
}
return result;
}
void TransactionApp::scheduleTransactionStart(SimTime startTime){
Enter_Method_Silent();//also used in Test environment so we need this to switch context
if(startTime == SimTime::ZERO){
scheduleAt(simTime(), new cMessage(SELFMESSAGE_START_TRANSACTION));
}else if (startTime >= simTime()){
scheduleAt(startTime, new cMessage(SELFMESSAGE_START_TRANSACTION));
}else{
throw cRuntimeError("Start Transaction time (%s) is in the past.",startTime.str().c_str());
}
}
std::vector<NetConfApplicationBase::Connection_t*> TransactionApp::getSwitchesInState(int state){
std::vector<NetConfApplicationBase::Connection_t*> resultVector;
for(auto it = switchStates.begin(); it != switchStates.end(); it++) {
if (it->second->isInState(state)) {
resultVector.push_back(it->first);
}
}
return resultVector;
}
void TransactionApp::determineLockOrder(){
for(auto& connection: _connections){
switchStates[&connection] = new SwitchState_t();
}
}
int TransactionApp::getTransactionState(){
return transactionState;
}
std::string TransactionApp::transactionAppStateToString(int state){
switch(state){
case TransactionAppState::BeginOfTransaction:
return "BeginOfTransaction";
case TransactionAppState::WaitOnLockResponse:
return "WaitOnLockResponse";
case TransactionAppState::WaitOnCandidateConfirmation:
return "WaitOnCandidateConfirmation";
case TransactionAppState::WaitOnChangeConfirmation:
return "WaitOnChangeConfirmation";
case TransactionAppState::WaitOnCommitExecution:
return "WaitOnCommitExecution";
case TransactionAppState::WaitOnDeleteOldConfiguration:
return "WaitOnDeleteOldConfiguration";
case TransactionAppState::WaitOnDeleteCandidate:
return "WaitOnDeleteCandidate";
case TransactionAppState::WaitOnUnlock:
return "WaitOnUnlock";
case TransactionAppState::ErrorState:
return "ErrorState";
case TransactionAppState::EndOfTransaction:
return "EndOfTransaction";
default:
return "invalid state";
}
}
NetConfApplicationBase::Connection_t* TransactionApp::findConnectionForReply(NetConfMessage_RPCReply* reply) {
//check if msg has context pointer
Connection_t* found = nullptr;
if(NetConfCtrlInfo* info = dynamic_cast<NetConfCtrlInfo*>(reply->getControlInfo())){
for (size_t i = 0; i < _connections.size(); i++) {
auto& connection = _connections[i];
if (connection.state
== ConnectionState_t::ConnectionStateEstablished
&& connection.session_id == info->getSession_id()) {
found = &connection;
break;
}
}
// check if connection is defined
if(found == nullptr){
throw cRuntimeError("undefined connection");
}
}
else {
throw cRuntimeError("undefined sessionInfo");
}
//delete sessionInfo;
return found;
}
bool TransactionApp::isFSMAlphabet(cMessage* msg){
return isStartTransactionEvent(msg) || isRPCReplyEvent(msg) || isLambdaEvent(msg);
}
bool TransactionApp::isStartTransactionEvent(cMessage* msg) {
return msg->isSelfMessage() && strcmp(msg->getName(), SELFMESSAGE_START_TRANSACTION) == 0;
}
bool TransactionApp::isRPCReplyEvent(cMessage* msg) {
if(dynamic_cast<NetConfMessage_RPCReply*>(msg)){
return true;
}
return false;
}
bool TransactionApp::isLambdaEvent(cMessage* msg) {
return msg == TransactionApp::LAMBDA_EVENT;
}
void TransactionApp::transitionToState(int nextState){
//execute exit action of current state
switch (transactionState) {
default:
break;
}
//switch state
transactionState = nextState;
// execute entry action of next state
Connection_t* connectionToLock = nullptr;
switch (nextState) {
case TransactionAppState::WaitOnLockResponse:
for(auto it = switchStates.begin(); it != switchStates.end(); it++) {
if(it->second->isInState(SwitchState::SwitchAvailable)){
connectionToLock = it->first;
break;
}
}
if(connectionToLock){
Configuration_t* config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Lock;
config->target = "running";
NetConfMessage_RPC* s_Switch_sperren = createNetConfRPCForConfiguration(connectionToLock, config, LOCK_MSG_ID);
sendDelayed(s_Switch_sperren, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
} else {
throw cRuntimeError("connection cannot locked");
}
break;
case TransactionAppState::ErrorState:
updatePhase(Phase::DEFAULT);
result = false;
emit(resultOfTransaction,result);
scheduleAt(simTime(), LAMBDA_EVENT);
break;
case TransactionAppState::EndOfTransaction:
updatePhase(Phase::DEFAULT);
result = true;
emit(resultOfTransaction,result);
emit(transactionDuration, true);
break;
default:
//throw cRuntimeError("cannot execute entry action of a state that has no entry action");
break;
}
}
void TransactionApp::finiteStateMachine(cMessage* msg){
Enter_Method_Silent();//also used in Test environment so we need this to switch context
bool eventHandled = false;
switch(transactionState){
case TransactionAppState::BeginOfTransaction:
eventHandled = handleMessageInBeginOfTransaction(msg);
break;
case TransactionAppState::WaitOnLockResponse:
eventHandled = handleMessageInWaitOnLockResponse(msg);
break;
case TransactionAppState::WaitOnCandidateConfirmation:
eventHandled = handleMessageInWaitOnCandidateConfirmation(msg);
break;
case TransactionAppState::WaitOnCandidateLockResponse:
eventHandled = handleMessageInWaitOnCandidateLockResponse(msg);
break;
case TransactionAppState::WaitOnChangeConfirmation:
eventHandled = handleMessageInWaitOnChangeConfirmation(msg);
break;
// case TransactionAppState::WaitOnTimestampConfirmation:
// eventHandled = handleMessageInWaitOnTimestampConfirmation(msg);
// break;
case TransactionAppState::ErrorState:
eventHandled = handleMessageInErrorState(msg);
break;
case TransactionAppState::WaitOnCommitExecution:
eventHandled = handleMessageInWaitOnCommitExecution(msg);
break;
case TransactionAppState::WaitOnDeleteOldConfiguration:
eventHandled = handleMessageInWaitOnDeleteOldConfiguration(msg);
break;
case TransactionAppState::WaitOnDeleteCandidate:
eventHandled = handleMessageInWaitOnDeleteCandidate(msg);
break;
case TransactionAppState::WaitOnUnlock:
eventHandled = handleMessageInWaitOnUnlock(msg);
break;
case TransactionAppState::EndOfTransaction:
break;
default:
cRuntimeError("Invalid State in FSM-TransactionApp");
break;
}
checkEventHandled(eventHandled, msg);
}
void TransactionApp::checkEventHandled(bool eventHandled, cMessage* msg){
if(!eventHandled){
std::string errorMsg = "Cannot handle event ";
errorMsg += msg->getFullName();
errorMsg += " in state ";
errorMsg += transactionAppStateToString(transactionState);
const char* errorMessage = errorMsg.c_str();
throw cRuntimeError(errorMessage);
}
}
bool TransactionApp::handleMessageInBeginOfTransaction(cMessage* msg){
if(isStartTransactionEvent(msg)){
emit(transactionDuration, true);
updatePhase(Phase::LOCK);
determineLockOrder();
transitionToState(TransactionAppState::WaitOnLockResponse);
return true;
}
return false;
}
bool TransactionApp::handleMessageInWaitOnLockResponse(cMessage* msg){
if(isRPCReplyEvent(msg)){
// received_Switch_locked
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if (((strcmp(reply->getMessage_id(), LOCK_MSG_ID) == 0) && (switchStates[con]->isInState(SwitchState::SwitchAvailable)))) {
switchStates[con]->hasLockedRunning = true;
std::vector<Connection_t*> lockedSwitches = getSwitchesInState(SwitchState::SwitchLocked);
if(lockedSwitches.size() < switchStates.size()){
transitionToState(TransactionAppState::WaitOnLockResponse);
return true;
}
else if(lockedSwitches.size() == switchStates.size()){
updatePhase(Phase::CHANGE);
// send_copy_config
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_CopyConfig;
config->source = "running";
config->target = "candidate";
NetConfMessage_RPC* s_Konfig_kopieren = createNetConfRPCForConfiguration(connection, config, COPY_CONFIG_MSG_ID);
sendDelayed(s_Konfig_kopieren, controllerProcessingTime, gate("applicationOut"));
}
}
transitionToState(TransactionAppState::WaitOnCandidateConfirmation);
return true;
}
}else{
throw cRuntimeError("reply is not the response of e_Switch_gesperrt and cannot locked");
}
}
// received_not_available
else if(dynamic_cast<NetConf_RPCReplyElement_Error*>(reply->getEncapsulatedPacket())){
if(strcmp(reply->getMessage_id(), LOCK_MSG_ID) != 0){
throw cRuntimeError("error-reply is not the response of e_bereits_belegt ");
}else{
std::vector<Connection_t*> lockedSwitches = getSwitchesInState(SwitchState::SwitchLocked);
if(lockedSwitches.size() == 0){
result = false;
emit(resultOfTransaction,result);
transitionToState(TransactionAppState::EndOfTransaction);
return true;
}else if(lockedSwitches.size() > 0){
Connection_t* con = findConnectionForReply(reply);
// send_unlock_switch
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
if(connection->remoteAddress == con->remoteAddress){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Unlock;
config->target = "running";
NetConfMessage_RPC* s_Switch_entsperren = createNetConfRPCForConfiguration(connection, config, UNLOCK_MSG_ID);
sendDelayed(s_Switch_entsperren, controllerProcessingTime, gate("applicationOut"));
}
}
}
switchStates[con]->hasLockedRunning = false;
result = false;
emit(resultOfTransaction,result);
transitionToState(TransactionAppState::WaitOnUnlock);
return true;
}
}
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnCandidateConfirmation(cMessage* msg){
if(isRPCReplyEvent(msg)){
// received_config_copied
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), COPY_CONFIG_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_Konfig_kopiert");
}else{
switchStates[con]->hasCandidate = true;
std::vector<Connection_t*> lockedSwitchesWithCandidate = getSwitchesInState(SwitchState::SwitchWithCandidate);
std::vector<Connection_t*> failedSwitch = getSwitchesInState(SwitchState::SwitchError);
if(failedSwitch.size() > 0){
if((lockedSwitchesWithCandidate.size() + failedSwitch.size()) == switchStates.size()){
transitionToState(TransactionAppState::ErrorState);
return true;
}
transitionToState(TransactionAppState::WaitOnCandidateConfirmation);
return true;
}
else if(lockedSwitchesWithCandidate.size() < switchStates.size()){
transitionToState(TransactionAppState::WaitOnCandidateConfirmation);
return true;
}
else if(lockedSwitchesWithCandidate.size() == switchStates.size()){
// send_lock_candidate_of_switch
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
config = new Configuration_t();
config->target = "candidate";
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Lock;
NetConfMessage_RPC* s_Switch_Kandidat_sperren = createNetConfRPCForConfiguration(connection, config, LOCK_CANDIDATE_MSG_ID);
sendDelayed(s_Switch_Kandidat_sperren, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
}
}
transitionToState(TransactionAppState::WaitOnCandidateLockResponse);
return true;
}
}
}else if(dynamic_cast<NetConf_RPCReplyElement_Error*>(reply->getEncapsulatedPacket())){
// received_creating_candidate_failed
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), COPY_CONFIG_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_Kandidat_fehlgeschlagen");
}else{
switchStates[con]->hasError = true;
std::vector<Connection_t*> lockedSwitchesWithCandidate = getSwitchesInState(SwitchState::SwitchWithCandidate);
std::vector<Connection_t*> failedSwitch = getSwitchesInState(SwitchState::SwitchError);
if((lockedSwitchesWithCandidate.size() == 0) && failedSwitch.size() == switchStates.size()){
//send_unlock_switch
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Unlock;
config->target = "running";
NetConfMessage_RPC* s_Switch_entsperren = createNetConfRPCForConfiguration(connection, config, UNLOCK_MSG_ID);
sendDelayed(s_Switch_entsperren, controllerProcessingTime, gate("applicationOut"));
}
}
transitionToState(TransactionAppState::WaitOnUnlock);
return true;
}
else if((lockedSwitchesWithCandidate.size() + failedSwitch.size()) < switchStates.size()){
transitionToState(TransactionAppState::WaitOnCandidateConfirmation);
return true;
}
else if((lockedSwitchesWithCandidate.size() + failedSwitch.size()) == switchStates.size()){
transitionToState(TransactionAppState::ErrorState);
return true;
}
}
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnCandidateLockResponse(cMessage* msg){
if(isRPCReplyEvent(msg)){
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
// received_switch_candidate_locked
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), LOCK_CANDIDATE_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_Switch_Kandidat_gesperrt");
}else{
switchStates[con]->hasLockedCandidate = true;
std::vector<Connection_t*> switchesWithLockedCandidate = getSwitchesInState(SwitchState::SwitchWithLockedCandidate);
if(switchesWithLockedCandidate.size() < switchStates.size()){
transitionToState(TransactionAppState::WaitOnCandidateLockResponse);
return true;
}else if(switchesWithLockedCandidate.size() == switchStates.size()){
// send_apply_changes
Connection_t* connection;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection && connection->configurations[0]->state == Configuration_t::ConfigurationState_t::ConfigurationStateWaiting){
connection->configurations[0]->target = "candidate";
NetConfMessage_RPC* s_Aenderung_durchfuehren = createNetConfRPCForConfiguration(connection, connection->configurations[0], std::to_string(CHANGE_MSG_ID+0));
sendDelayed(s_Aenderung_durchfuehren, controllerProcessingTime, gate("applicationOut"));
connection->configurations[0]->state = Configuration_t::ConfigurationState_t::ConfigurationStateRequested;
}
}
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
}
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnChangeConfirmation(cMessage* msg){
if(isRPCReplyEvent(msg)){
// receive_apply_changes
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
Connection_t* con = findConnectionForReply(reply);
int idx = atoi(reply->getMessage_id()) - CHANGE_MSG_ID;
if(con->configurations[idx]->state != Configuration_t::ConfigurationState_t::ConfigurationStateRequested) {
throw cRuntimeError(" reply is not the response for last change of e_Aenderung_durchgefuehrt");
}
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
con->configurations[idx]->state = Configuration_t::ConfigurationState_t::ConfigurationStateSuccess;
if(getSwitchesInState(SwitchState::SwitchError).size() > 0){
switchStates[con]->hasConfiguration = true;
if(getSwitchesInState(SwitchState::SwitchError).size()+getSwitchesInState(SwitchState::SwitchWithChangedCandidateConfiguration).size() == switchStates.size()){
transitionToState(TransactionAppState::ErrorState);
return true;
}else{
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
}
std::vector<Configuration_t*> configsInConnection = con->configurations;
int i;
for(i = 0; i < configsInConnection.size(); i++){
if(configsInConnection[i]->state == Configuration_t::ConfigurationState_t::ConfigurationStateWaiting){
con->configurations[i]->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig;
con->configurations[i]->target = "candidate";
NetConfMessage_RPC* s_Aenderung_durchfuehren = createNetConfRPCForConfiguration(con, con->configurations[i], std::to_string(CHANGE_MSG_ID+i));
sendDelayed(s_Aenderung_durchfuehren, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
con->configurations[i]->state = Configuration_t::ConfigurationState_t::ConfigurationStateRequested;
break;//only send next one
}
}
if(i >= configsInConnection.size()){
//no more changes sent
switchStates[con]->hasConfiguration = true;
}
if((getSwitchesInState(SwitchState::SwitchWithChangedCandidateConfiguration).size() == switchStates.size())
&& (getSwitchesInState(SwitchState::SwitchError).size() == 0)){ // no more changes for all switches
// transition to next state
Connection_t* connection;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
Configuration_t* config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Commit;
NetConfMessage_RPC* s_Commit_freigeben = createNetConfRPCForConfiguration(connection, config, COMMIT_APPROVED_MSG_ID);
sendDelayed(s_Commit_freigeben, controllerProcessingTime, gate("applicationOut"));
updatePhase(Phase::CONFIRMATION);
}
}
transitionToState(TransactionAppState::WaitOnCommitExecution);
return true;
}
else { // done with changes || no more changes for this switch
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
}
else if(dynamic_cast<NetConf_RPCReplyElement_Error*>(reply->getEncapsulatedPacket())){
// received_applaying_changes_failed
con->configurations[idx]->state = Configuration_t::ConfigurationState_t::ConfigurationStateError;
switchStates[con]->hasError = true;
std::vector<Connection_t*> switchesWithChangedCandidateConfig = getSwitchesInState(SwitchState::SwitchWithChangedCandidateConfiguration);
std::vector<Connection_t*> failedSwitch = getSwitchesInState(SwitchState::SwitchError);
if((switchesWithChangedCandidateConfig.size()+failedSwitch.size()) < switchStates.size()){
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
else if((switchesWithChangedCandidateConfig.size()+failedSwitch.size()) == switchStates.size()){
transitionToState(TransactionAppState::ErrorState);
return true;
}
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnCommitExecution(cMessage* msg){
if(isRPCReplyEvent(msg)){
// received_execute_commit
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), COMMIT_APPROVED_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_Commit_ausgefuehrt");
}else{
switchStates[con]->hasCommited = true;
std::vector<Connection_t*> commitedSwitches = getSwitchesInState(SwitchState::SwitchCommited);
if(switchStates.size() > commitedSwitches.size()){
transitionToState(TransactionAppState::WaitOnCommitExecution);
return true;
}else if(switchStates.size() == commitedSwitches.size()){
updatePhase(Phase::UNLOCK);
// send_delete_old_configuration
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_DeleteConfig;
config->target = "candidate";
NetConfMessage_RPC* s_alte_Konfig_loeschen = createNetConfRPCForConfiguration(connection, config, DELETE_OLD_CONFIG_MSG_ID);
sendDelayed(s_alte_Konfig_loeschen, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
}
}
transitionToState(TransactionAppState::WaitOnDeleteOldConfiguration);
return true;
}
}
} else {
// this is a hardware fault and not handled in transaction
throw cRuntimeError(" Reply for commit execution is not ok response of e_Commit_ausgefuehrt");
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnDeleteOldConfiguration(cMessage* msg){
if(isRPCReplyEvent(msg)){
// received_delete_old_configuration
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), DELETE_OLD_CONFIG_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_alte_Konfig_geloescht");
}else{
switchStates[con]->hasCandidate = false;
switchStates[con]->hasLockedCandidate = false;
std::vector<Connection_t*> switchesWithoutOldConfig = getSwitchesInState(SwitchState::SwitchWithoutOldConfig);
if(switchesWithoutOldConfig.size() == switchStates.size()){
// send_unlock_switch
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Unlock;
config->target = "running";
NetConfMessage_RPC* s_Switch_entsperren = createNetConfRPCForConfiguration(connection, config, UNLOCK_MSG_ID);
sendDelayed(s_Switch_entsperren, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
}
}
transitionToState(TransactionAppState::WaitOnUnlock);
return true;
}else if(switchesWithoutOldConfig.size() < switchStates.size()){
transitionToState(TransactionAppState::WaitOnDeleteOldConfiguration);
return true;
}
}
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnDeleteCandidate(cMessage* msg){
if(isRPCReplyEvent(msg)){
// receive_candidate_deleted
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), DELETE_CANDIDATE_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_Kandidat_geloescht");
}else{
switchStates[con]->hasCandidate = false;
switchStates[con]->hasLockedCandidate = false;
std::vector<Connection_t*> switchesWithoutCandidate = getSwitchesInState(SwitchState::SwitchWithoutCandidate);
if(switchStates.size() > switchesWithoutCandidate.size()){
transitionToState(TransactionAppState::WaitOnDeleteCandidate);
return true;
}else if(switchStates.size() == switchesWithoutCandidate.size()){
// send_unlock_switch
Connection_t* connection;
Configuration_t* config;
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Unlock;
config->target = "running";
NetConfMessage_RPC* s_Switch_entsperren = createNetConfRPCForConfiguration(connection, config, UNLOCK_MSG_ID);
sendDelayed(s_Switch_entsperren, controllerProcessingTime, gate("applicationOut"));
}
}
transitionToState(TransactionAppState::WaitOnUnlock);
return true;
}
}
}
}
return false;
}
bool TransactionApp::handleMessageInWaitOnUnlock(cMessage* msg){
if(isRPCReplyEvent(msg)){
// receive_switch_unlocked
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), UNLOCK_MSG_ID) != 0){
throw cRuntimeError(" reply is not the response of e_Switch_sperren");
}else{
switchStates[con]->hasLockedRunning = false;
std::vector<Connection_t*> unlockedSwitches = getSwitchesInState(SwitchState::SwitchUnlocked);
if(unlockedSwitches.size() < switchStates.size()){
transitionToState(TransactionAppState::WaitOnUnlock);
return true;
}else if(unlockedSwitches.size() == switchStates.size()){
updatePhase(Phase::UNLOCK);
transitionToState(TransactionAppState::EndOfTransaction);
return true;
}
}
}
}
return false;
}
bool TransactionApp::handleMessageInErrorState(cMessage* msg){
if(isLambdaEvent(msg)){
// send_delete_candidate
Connection_t* connection;
Configuration_t* config;
result = false;
emit(resultOfTransaction,result);
for(auto it = switchStates.begin(); it != switchStates.end(); it++){
connection = it->first;
if(connection && switchStates[connection]->hasCandidate){
config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_DeleteConfig;
config->target = "candidate";
NetConfMessage_RPC* s_Kandidat_loeschen = createNetConfRPCForConfiguration(connection, config, DELETE_CANDIDATE_MSG_ID);
sendDelayed(s_Kandidat_loeschen, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
}
}
transitionToState(TransactionAppState::WaitOnDeleteCandidate);
return true;
}
return false;
}
} // namespace SDN4CoRE
| 38,611
|
C++
|
.cc
| 764
| 37.736911
| 184
| 0.619161
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,179
|
TimeSynchronousTransactionApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/transactionModel/TimeSynchronousTransactionApp.cc
|
//
// c Mohammad Fazel Soltani, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//CoRE4INET
#include "core4inet/scheduler/oscillator/Oscillator.h"
#include "core4inet/scheduler/timer/Timer.h"
//SDN4CoRE
#include <sdn4core/netconf/applications/transactionModel/TimeSynchronousTransactionApp.h>
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserCollection.h>
#include <sdn4core/utility/xml/XMLUtility.h>
namespace SDN4CoRE{
Define_Module(TimeSynchronousTransactionApp);
void TimeSynchronousTransactionApp::initialize()
{
TransactionApp::initialize();
_period = dynamic_cast<CoRE4INET::Period*>(this->getParentModule()->getParentModule()->getSubmodule("scheduler")->getSubmodule("period",_syncPeriod));
controllerProcessingTime = this->par("controllerProcessingTime").doubleValue();
}
std::vector<NetConfApplicationBase::Connection_t*> TimeSynchronousTransactionApp::getSwitchesInState(int state){
std::vector<NetConfApplicationBase::Connection_t*> resultVector;
for(auto it = switchStates.begin(); it != switchStates.end(); it++) {
if (((TimeSynchronousTransactionApp::SwitchState_s*)(it->second))->isInState(state)) {
resultVector.push_back(it->first);
}
}
return resultVector;
}
void TimeSynchronousTransactionApp::determineLockOrder(){
for(auto& connection: _connections){
switchStates[&connection] = new TimeSynchronousTransactionApp::SwitchState_t();
}
}
Configuration_t* TimeSynchronousTransactionApp::getCommitTimestampConfig(NetConfConfigCommitTimestamp::CommitTimestamp_t timestamp){
NetConfConfigCommitTimestamp* netConfConfigCommitTimestamp = new NetConfConfigCommitTimestamp();
netConfConfigCommitTimestamp->setCommitTimestamp(timestamp);
Configuration_t* config = new Configuration_t();
config->data = netConfConfigCommitTimestamp;
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig;
config->target = "candidate";
config->filter = new NetConfFilter();
config->state = Configuration_t::ConfigurationState_t::ConfigurationStateWaiting;
return config;
}
NetConfConfigCommitTimestamp::CommitTimestamp_t TimeSynchronousTransactionApp::determineTimestamp()
{
double wireDelay = 1/(this->par("signalDelay").doubleValue());
double switchDelay = this->par("switchDelay").doubleValue();
double switchProcessingTime = this->par("switchProcessingTime").doubleValue();
double bitTransferTime = 1 / (this->par("bitRate").doubleValue());
int ethernetFrameSizes[] = {SEND_TIMESTAMP_MSG_SIZE, ACK_TIMESTAMP_MSG_SIZE, SEND_COMMIT_MSG_SIZE};
double sumOfLatencies = 0;
double queuingDelay = MAX_ETHERNET_FRAME_SIZE * bitTransferTime;
std::vector<std::string> distanceAndHopPerSwitches = cStringTokenizer(par("distanceAndHopsToSwitches"), ";").asVector();
if(distanceAndHopPerSwitches.size() == 1)
{
std::vector<int> values = cStringTokenizer(distanceAndHopPerSwitches[0].c_str(), ",").asIntVector();
int wireLength = values[0];
int hop = values[1];
for(int i = 0; i < distanceAndHopPerSwitches.size(); i++)
{
for(int k = 0; k < 3; k++)
{
if(k == 2)
{
_sumOfLastLatencies += wireDelay * wireLength + (hop + 1) * ethernetFrameSizes[k] * bitTransferTime + (hop * switchDelay) + ((hop + 1) * queuingDelay);
}
sumOfLatencies += wireDelay * wireLength + (hop + 1) * ethernetFrameSizes[k] * bitTransferTime + (hop * switchDelay) + ((hop + 1) * queuingDelay);
}
}
}
else if(distanceAndHopPerSwitches.size() == this->_connections.size())
{
std::vector<int> values;
std::vector<int> wireLengths;
std::vector<int> hops;
for(int i = 0 ; i < distanceAndHopPerSwitches.size(); i++)
{
values = cStringTokenizer(distanceAndHopPerSwitches[i].c_str(), ",").asIntVector();
wireLengths.push_back(values[0]);
hops.push_back(values[1]);
}
for(int i = 0; i < this->_connections.size(); i++)
{
for(int k = 0; k < 3; k++)
{
if(k == 2)
{
_sumOfLastLatencies += wireDelay * wireLengths[i] + (hops[i] + 1) * ethernetFrameSizes[k] * bitTransferTime + (hops[i] * switchDelay) + ((hops[i] + 1) * queuingDelay);
}
sumOfLatencies += wireDelay * wireLengths[i] + (hops[i] + 1) * ethernetFrameSizes[k] * bitTransferTime + (hops[i] * switchDelay) + ((hops[i] + 1) * queuingDelay);
}
}
}
else
{
throw cRuntimeError("number of switches are not %d", this->_connections.size());
}
double buffer = sumOfLatencies + (2*switchProcessingTime) + (2*controllerProcessingTime);
CoRE4INET::Timer* timer = dynamic_cast<CoRE4INET::Timer*>(this->getParentModule()->getParentModule()->getSubmodule("scheduler")->getSubmodule("timer"));
// period length
CoRE4INET::Oscillator* oscillator = timer->getOscillator();
double periodLength = _period->getCycleTicks() * oscillator->getPreciseTick().dbl();
// current cycles
uint32_t currentCycles = _period->getCycles();
_timestamp.cycle = currentCycles + static_cast<uint32_t>(std::ceil(buffer/periodLength));
_timestamp.time = buffer + timer->getTotalSimTime().dbl();
_timestamp.period = _syncPeriod;
_timestamp.executeAtStartOfPeriod = this->par("executeAtStartOfPeriod");
return _timestamp;
}
bool TimeSynchronousTransactionApp::checkCommitrelease()
{
bool commitRelease = false;
double switchProcessingTime = this->par("switchProcessingTime").doubleValue();
double buffer = _sumOfLastLatencies + switchProcessingTime;
uint32_t currentCycles = _period->getCycles();
// period length
CoRE4INET::Oscillator* oscillator = dynamic_cast<CoRE4INET::Oscillator*>(this->getParentModule()->getParentModule()->getSubmodule("scheduler")->getSubmodule("oscillator"));
double periodLength = _period->getCycleTicks() * oscillator->getPreciseTick().dbl();
uint32_t calculatedExecutionCycle = currentCycles + static_cast<uint32_t>(std::ceil(buffer/periodLength));
if( _timestamp.cycle > calculatedExecutionCycle)
{
commitRelease = true;
}
return commitRelease;
}
std::string TimeSynchronousTransactionApp::transactionAppStateToString(int state)
{
switch(state)
{
case TransactionAppState::WaitOnTimestampConfirmation:
return "WaitOnTimestampConfirmation";
default:
return TransactionApp::transactionAppStateToString(state);
}
}
void TimeSynchronousTransactionApp::finiteStateMachine(cMessage* msg)
{
Enter_Method_Silent();//also used in Test environment so we need this to switch context
bool eventHandled = false;
switch(transactionState){
case TransactionAppState::WaitOnTimestampConfirmation:
eventHandled = handleMessageInWaitOnTimestampConfirmation(msg);
checkEventHandled(eventHandled, msg);
break;
default:
TransactionApp::finiteStateMachine(msg);
break;
}
}
bool TimeSynchronousTransactionApp::handleMessageInWaitOnChangeConfirmation(cMessage* msg)
{
if(isRPCReplyEvent(msg))
{
// received_applied_changes
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
Connection_t* con = findConnectionForReply(reply);
int idx = atoi(reply->getMessage_id()) - CHANGE_MSG_ID;
if(con->configurations[idx]->state != Configuration_t::ConfigurationState_t::ConfigurationStateRequested)
{
throw cRuntimeError(" reply is not the response for last change of e_Aenderung_durchgefuehrt");
}
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket()))
{
con->configurations[idx]->state = Configuration_t::ConfigurationState_t::ConfigurationStateSuccess;
if(getSwitchesInState(SwitchState::SwitchError).size() > 0)
{
switchStates[con]->hasConfiguration = true;
if(getSwitchesInState(SwitchState::SwitchError).size()+
getSwitchesInState(SwitchState::SwitchWithChangedCandidateConfiguration).size() == switchStates.size())
{
transitionToState(TransactionAppState::ErrorState);
return true;
}
else
{
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
}
std::vector<Configuration_t*> configsInConnection = con->configurations;
int i;
for(i = 0; i < configsInConnection.size(); i++)
{
if(configsInConnection[i]->state == Configuration_t::ConfigurationState_t::ConfigurationStateWaiting)
{
con->configurations[i]->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig;
con->configurations[i]->target = "candidate";
NetConfMessage_RPC* s_Aenderung_durchfuehren = createNetConfRPCForConfiguration(con, con->configurations[i], std::to_string(CHANGE_MSG_ID+i));
sendDelayed(s_Aenderung_durchfuehren, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
con->configurations[i]->state = Configuration_t::ConfigurationState_t::ConfigurationStateRequested;
break;//only send next one
}
}
if(i >= configsInConnection.size())
{
//no more changes sent
switchStates[con]->hasConfiguration = true;
}
if((getSwitchesInState(SwitchState::SwitchWithChangedCandidateConfiguration).size() == switchStates.size())
&& (getSwitchesInState(SwitchState::SwitchError).size() == 0))
{
// transition to next state
NetConfConfigCommitTimestamp::CommitTimestamp_t timestamp = determineTimestamp();
// send_timestamp
Connection_t* connection;
for(auto it = switchStates.begin(); it != switchStates.end(); it++)
{
if(it->second->isInState(SwitchState::SwitchWithChangedCandidateConfiguration))
{
connection = it->first;
if(connection){
Configuration_t* config = getCommitTimestampConfig(timestamp);
NetConfMessage_RPC* s_Zeitstempel = createNetConfRPCForConfiguration(connection, config, TIMESTAMP_MSG_ID);
delete config; // delete the config as it has been duplicated during encapsulation in to NetConfMessage_RPC.
sendDelayed(s_Zeitstempel, controllerProcessingTime, gate("applicationOut"));
updatePhase(Phase::CONFIRMATION);
emit(numSent, 1L);
}
}
}
transitionToState(TransactionAppState::WaitOnTimestampConfirmation);
return true;
}
else
{ // done with changes || no more changes for this switch
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
}
else if(dynamic_cast<NetConf_RPCReplyElement_Error*>(reply->getEncapsulatedPacket())){
// received_applying_changes_failed
con->configurations[idx]->state = Configuration_t::ConfigurationState_t::ConfigurationStateError;
switchStates[con]->hasError = true;
std::vector<Connection_t*> switchesWithChangedCandidateConfig = getSwitchesInState(SwitchState::SwitchWithChangedCandidateConfiguration);
std::vector<Connection_t*> failedSwitch = getSwitchesInState(SwitchState::SwitchError);
if((switchesWithChangedCandidateConfig.size()+failedSwitch.size()) < switchStates.size())
{
transitionToState(TransactionAppState::WaitOnChangeConfirmation);
return true;
}
else if((switchesWithChangedCandidateConfig.size()+failedSwitch.size()) == switchStates.size())
{
transitionToState(TransactionAppState::ErrorState);
return true;
}
}
}
return false;
}
bool TimeSynchronousTransactionApp::handleMessageInWaitOnTimestampConfirmation(cMessage* msg)
{
if(isRPCReplyEvent(msg))
{
// received_timestamp_accepted
NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg);
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket()))
{
Connection_t* con = findConnectionForReply(reply);
if(strcmp(reply->getMessage_id(), TIMESTAMP_MSG_ID) != 0)
{
throw cRuntimeError(" reply is not the response of e_Zeitstempel_akzeptiert");
}
else
{
((TimeSynchronousTransactionApp::SwitchState_s*)switchStates[con])->hasCommitTimeStamp = true;
std::vector<Connection_t*> switchesWithTimestamp = getSwitchesInState(SwitchState::SwitchWithTimestamp);
std::vector<Connection_t*> failedSwitch = getSwitchesInState(SwitchState::SwitchError);
if(failedSwitch.size() > 0 &&
((switchesWithTimestamp.size()+failedSwitch.size()) == switchStates.size()))
{
transitionToState(TransactionAppState::ErrorState);
return true;
}
else if(switchesWithTimestamp.size() < switchStates.size())
{
transitionToState(TransactionAppState::WaitOnTimestampConfirmation);
return true;
}
else if(switchesWithTimestamp.size() == switchStates.size())
{
if(!checkCommitrelease())
{
transitionToState(TransactionAppState::ErrorState);
return true;
}
else
{
Connection_t* connection;
for(auto it = switchStates.begin(); it != switchStates.end(); it++)
{
connection = it->first;
if(connection){
Configuration_t* config = new Configuration_t();
config->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_Commit;
NetConfMessage_RPC* s_Commit_freigeben = createNetConfRPCForConfiguration(connection, config, COMMIT_APPROVED_MSG_ID);
sendDelayed(s_Commit_freigeben, controllerProcessingTime, gate("applicationOut"));
emit(numSent, 1L);
}
}
transitionToState(TransactionAppState::WaitOnCommitExecution);
return true;
}
}
}
}
else if(dynamic_cast<NetConf_RPCReplyElement_Error*>(reply->getEncapsulatedPacket()))
{
// received_timestamp_missed
if(strcmp(reply->getMessage_id(), TIMESTAMP_MSG_ID) != 0)
{
throw cRuntimeError(" reply is not the response of e_Zeitpunkt_ ueberschritten");
}
else
{
Connection_t* con = findConnectionForReply(reply);
switchStates[con]->hasError = true;
std::vector<Connection_t*> switchesWithTimestamp = getSwitchesInState(SwitchState::SwitchWithTimestamp);
std::vector<Connection_t*> failedSwitch = getSwitchesInState(SwitchState::SwitchError);
if((switchesWithTimestamp.size() + failedSwitch.size()) < switchStates.size())
{
transitionToState(TransactionAppState::WaitOnTimestampConfirmation);
return true;
}
else if((switchesWithTimestamp.size() + failedSwitch.size()) == switchStates.size())
{
transitionToState(TransactionAppState::ErrorState);
return true;
}
}
}
}
return false;
}
} // namespace SDN4CoRE
| 17,508
|
C++
|
.cc
| 349
| 38.676218
| 187
| 0.631579
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,180
|
TransactionModelTest.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/transactionModel/transactionModelTest/TransactionModelTest.cc
|
//
// c Mohammad Fazel Soltani for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/applications/transactionModel/transactionModelTest/TransactionModelTest.h>
namespace SDN4CoRE{
Define_Module(TransactionModelTest);
NetConfApplicationBase::Connection_t TransactionModelTest::initConnectionOne(){
// initialize con1
NetConfApplicationBase::Connection_t con1;
con1.connectAt = std::stod("0.01");
con1.localPort = 1;
con1.remoteAddress = "switch1";
con1.remotePort = 830;
con1.session_id = 1;
con1.state = NetConfApplicationBase::ConnectionState_t::ConnectionStateEstablished;
// init config1
Configuration_t* config1 = new Configuration_t();
config1->executeAt = std::stod("0.2");
config1->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig;
config1->state = Configuration_t::ConfigurationState_t::ConfigurationStateWaiting;
config1->data = new NetConfConfig();
config1->filter = new NetConfFilter();
config1->target = "candidate";
// init config2
Configuration_t* config2 = new Configuration_t();
config2->executeAt = std::stod("0.5");
config2->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig;
config2->state = Configuration_t::ConfigurationState_t::ConfigurationStateWaiting;
config2->data = new NetConfConfig();
config2->filter = new NetConfFilter();
config2->target = "candidate";
// put configs in con1
con1.configurations.push_back(config1);
con1.configurations.push_back(config2);
return con1;
}
NetConfApplicationBase::Connection_t TransactionModelTest::initConnectionTwo(){
// initialize con2
NetConfApplicationBase::Connection_t con2;
con2.connectAt = std::stod("0.02");
con2.localPort = 2;
con2.remoteAddress = "switch2";
con2.remotePort = 830;
con2.session_id = 2;
con2.state = NetConfApplicationBase::ConnectionState_t::ConnectionStateEstablished;
// init config1
Configuration_t* config1 = new Configuration_t();
config1->executeAt = std::stod("0.2");
config1->type = Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig;
config1->state = Configuration_t::ConfigurationState_t::ConfigurationStateWaiting;
config1->data = new NetConfConfig();
config1->filter = new NetConfFilter();
config1->target = "candidate";
// put config1 in con2
con2.configurations.push_back(config1);
return con2;
}
void TransactionModelTest::initConnections(){
std::vector<NetConfApplicationBase::Connection_t> connections;
NetConfApplicationBase::Connection_t con1 = initConnectionOne();
NetConfApplicationBase::Connection_t con2 = initConnectionTwo();
connections.push_back(con1);
connections.push_back(con2);
_timeSynchronousTransactionApp->setConnnections(connections);
}
void TransactionModelTest::initialize(){
_timeSynchronousTransactionApp = dynamic_cast<TimeSynchronousTransactionApp*>(this->getParentModule()->getSubmodule("controller")->getSubmodule("netconf")->getSubmodule("timeSynchronousTransactionApp"));
scheduleAt(simTime(), new cMessage("Reset FSM"));
_partTwoMessage = new cMessage("PartTwo");
_testCase = this->par("testCaseNumber");
}
void TransactionModelTest::resetFSM(){
initConnections();
_timeSynchronousTransactionApp->scheduleTransactionStart();
}
void TransactionModelTest::handleMessage(omnetpp::cMessage* msg){
static bool first = true;
bool success = false;
bool finish = false;
if(msg->isSelfMessage() && strcmp(msg->getName(), "Reset FSM") == 0){
resetFSM();
}
else if(!msg->isSelfMessage() && first){
first = false;
switch(_testCase) {
case 1:
success = stateAndTransitionCoverageSuccesful();
if(success){
std::cout << "Success | stateAndTransitionCoverageSuccesful()" << std::endl;
}
finish = true;
break;
case 2:
success = stateAndTransitionCoverageFailure();
if(success){
std::cout << "Success | stateAndTransitionCoverageFailure()" << std::endl;
}
finish = true;
break;
case 3:
success = transitionCoverageAlreadyLocked();
if(success){
std::cout << "Success | transitionCoverageAlreadyLocked()" << std::endl;
}
finish = true;
break;
case 4:
success = transitionCoverageAlreadyLockedNext();
if(success){
std::cout << "Success | transitionCoverageAlreadyLocked2()" << std::endl;
}
finish = true;
break;
case 5:
success = transitionCoverageAllCandidatesFailed();
if(success){
std::cout << "Success | transitionCoverageAllCandidatesFailed()" << std::endl;
}
finish = true;
break;
case 6:
success = transitionCoverageFirstCandidateFailed();
if(success){
std::cout << "Success | transitionCoverageFirstCandidateFailed()" << std::endl;
}
finish = true;
break;
case 7:
success = transitionCoverageLastCandidateFailed();
if(success){
std::cout << "Success | transitionCoverageLastCandidateFailed()" << std::endl;
}
finish = true;
break;
case 8:
success = transitionCoverageFirstChangeFails();
if(success){
std::cout << "Success | transitionCoverageFirstChangeFails()" << std::endl;
}
finish = true;
break;
case 9:
success = transitionCoverageNextChangeFails();
if(success){
std::cout << "Success | transitionCoverageNextChangeFails()" << std::endl;
}
finish = true;
break;
case 10:
success = transitionCoverageFirstTimestampFail();
if(success){
std::cout << "Success | transitionCoverageFirstTimestampFail()" << std::endl;
}
finish = true;
break;
case 11:
success = transitionCoverageLastTimestampFail();
if(success){
std::cout << "Success | transitionCoverageLastTimestampFail()" << std::endl;
}
finish = true;
break;
case 12:
success = transitionCoverageCommitReleasePartOne();
if(success){
std::cout << "Success | transitionCoverageCommitReleasePartOne()" << std::endl;
}
scheduleAt(simTime() + 1 ,_partTwoMessage);
break;
}
}
else if(msg->isSelfMessage() && strcmp(msg->getName(), "PartTwo") == 0) {
switch (_testCase) {
case 12:
success = transitionCoverageCommitReleasePartTwo();
if(success){
std::cout << "Success | transitionCoverageCommitReleasePartTwo()" << std::endl;
}
finish = true;
break;
default:
break;
}
}
if(finish){
endSimulation();
}
delete msg;
}
NetConfCtrlInfo* TransactionModelTest::getControlInfo(std::string controlInfoMessageId, int sessionId){
NetConfCtrlInfo* controlInfo = new NetConfCtrlInfo();
controlInfo->setSession_id(sessionId);
controlInfo->setMessage_id(controlInfoMessageId.c_str());
return controlInfo;
}
NetConfMessage_RPCReply* TransactionModelTest::getReplyOkMsg(std::string msgId, std::string controlInfoMessageId, int sessionId){
NetConfMessage_RPCReply* msg = new NetConfMessage_RPCReply();
msg->setMessage_id(msgId.c_str());
msg->setControlInfo(getControlInfo(controlInfoMessageId.c_str(),sessionId));
NetConf_RPCReplyElement_Ok* ok = new NetConf_RPCReplyElement_Ok();
msg->encapsulate(ok);
return msg;
}
NetConfMessage_RPCReply* TransactionModelTest::getReplyErrorMsg(std::string msgId, std::string controlInfoMessageId, int sessionId){
NetConfMessage_RPCReply* msg = new NetConfMessage_RPCReply();
msg->setMessage_id(msgId.c_str());
msg->setControlInfo(getControlInfo(controlInfoMessageId.c_str(),sessionId));
NetConf_RPCReplyElement_Error* error = new NetConf_RPCReplyElement_Error();
msg->encapsulate(error);
return msg;
}
bool TransactionModelTest::stateAndTransitionCoverageFailure(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return true;
}
bool TransactionModelTest::stateAndTransitionCoverageSuccesful(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID+1), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnTimestampConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCommitExecution){
std::cout << "Failure | Transaction State has to be in WaitOnTimestampConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COMMIT_APPROVED_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCommitExecution){
std::cout << "Failure | Transaction State has to be in WaitOnCommit_Execution" << std::endl;
return false;
}
msg = getReplyOkMsg(COMMIT_APPROVED_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteOldConfiguration){
std::cout << "Failure | Transaction State has to be in WaitOnCommit_Execution" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_OLD_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteOldConfiguration){
std::cout << "Failure | Transaction State has to be in WaitOnCommit_Execution" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_OLD_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnCommit_Execution" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnCommit_Execution" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in WaitOnCommit_Execution" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageAlreadyLocked(){
NetConfMessage_RPCReply* msg;
msg = getReplyErrorMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageAlreadyLockedNext(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyErrorMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageAllCandidatesFailed(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyErrorMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageLastCandidateFailed(){
return stateAndTransitionCoverageFailure();
}
bool TransactionModelTest::transitionCoverageFirstCandidateFailed(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageFirstChangeFails(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID+1), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageNextChangeFails(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageFirstTimestampFail(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID+1), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(TIMESTAMP_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnTimestampConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageLastTimestampFail(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID+1), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnTimestampConfirmation" << std::endl;
return false;
}
msg = getReplyErrorMsg(TIMESTAMP_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageCommitReleaseFailed(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID+1), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnTimestampConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageCommitReleasePartOne(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(LOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(COPY_CONFIG_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnCandidateLockResponse){
std::cout << "Failure | Transaction State has to be in WaitOnCandidateLockResponse" << std::endl;
return false;
}
msg = getReplyOkMsg(LOCK_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID), "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnChangeConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(std::to_string(CHANGE_MSG_ID+1), "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnChangeConfirmation" << std::endl;
return false;
}
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnTimestampConfirmation){
std::cout << "Failure | Transaction State has to be in WaitOnTimestampConfirmation" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
bool TransactionModelTest::transitionCoverageCommitReleasePartTwo(){
NetConfMessage_RPCReply* msg;
msg = getReplyOkMsg(TIMESTAMP_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::ErrorState){
std::cout << "Failure | Transaction State has to be in ErrorState" << std::endl;
return false;
}
_timeSynchronousTransactionApp->finiteStateMachine(_timeSynchronousTransactionApp->LAMBDA_EVENT);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnDeleteCandidate){
std::cout << "Failure | Transaction State has to be in WaitOnDeleteCandidate" << std::endl;
return false;
}
msg = getReplyOkMsg(DELETE_CANDIDATE_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "0", 1);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::WaitOnUnlock){
std::cout << "Failure | Transaction State has to be in WaitOnUnlock" << std::endl;
return false;
}
msg = getReplyOkMsg(UNLOCK_MSG_ID, "1", 2);
_timeSynchronousTransactionApp->finiteStateMachine(msg);
if(_timeSynchronousTransactionApp->transactionState != TimeSynchronousTransactionApp::TransactionAppState::EndOfTransaction){
std::cout << "Failure | Transaction State has to be in EndOfTransaction" << std::endl;
return false;
}
return _timeSynchronousTransactionApp->result;
}
} // namespace SDN4CoRE
| 61,726
|
C++
|
.cc
| 1,076
| 50.874535
| 207
| 0.737962
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,181
|
NetConfAppConfigParserMultipart.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/multipart/NetConfAppConfigParserMultipart.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserCollection.h>
#include <sdn4core/netconf/applications/configparser/multipart/NetConfAppConfigParserMultipart.h>
#include <sdn4core/netconf/datastructures/multipart/NetConfConfigMultipart.h>
namespace SDN4CoRE {
NetConfConfig* SDN4CoRE::NetConfAppConfigParserMultipart::getConfigDataFor( cXMLElement* element) {
cXMLElementList configuresXML = element->getChildrenByTagName("configure");
NetConfConfigMultipart* multiPartConfig = new NetConfConfigMultipart();
for (auto configureXML : configuresXML) {
if(auto newConfig = NetConfAppConfigParserCollection::getConfigDataFor(configureXML)){
multiPartConfig->addConfiguration(newConfig);
}else{
throw new cRuntimeError("NetConfAppConfigParserMultipart: unknown config");
}
}
return multiPartConfig;
}
} /* namespace SDN4CoRE */
| 1,648
|
C++
|
.cc
| 34
| 45.294118
| 99
| 0.782338
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,182
|
NetConfAppConfigParserOpenFlow.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/openflow/NetConfAppConfigParserOpenFlow.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/openflow/NetConfAppConfigParserOpenFlow.h>
namespace SDN4CoRE {
NetConfConfig* NetConfAppConfigParserOpenFlow::getConfigDataFor(cXMLElement* element){
OF_NetConfConfigFlowMod* configData = new OF_NetConfConfigFlowMod();
cXMLElementList configsXML = element->getChildrenByTagName("config");
for(cXMLElement* config: configsXML){
OF_NetConfConfigFlowMod::OF_FlowTableConfig_t* tableConfig = new OF_NetConfConfigFlowMod::OF_FlowTableConfig_t();
tableConfig->command = parseCommand(config->getAttribute("operation"));
tableConfig->table_id = atoi(config->getAttribute("tableIndex"));
for(cXMLElement* entry: config->getChildrenByTagName("flowEntry")){
OF100_FlowTableEntry* tmp = new OF100_FlowTableEntry(entry);
tableConfig->flowTableEntries.push_back(tmp);
}
if(tableConfig->flowTableEntries.empty()){
throw cRuntimeError("No flow entries to change in flowtable config");
}
configData->addFlowTableConfig(tableConfig);
}
if(configData->getFlowTableConfigs().empty()){
throw cRuntimeError("No configuration in flow table config data");
}
return dynamic_cast<NetConfConfig*> (configData);
}
OF_NetConfConfigFlowMod::commands NetConfAppConfigParserOpenFlow::parseCommand(const char* command){
if(!strcmp(command, "ADD_FLOW")){
return OF_NetConfConfigFlowMod::ADD_FLOW;
}else if(!strcmp(command, "MODIFY_FLOW")){
return OF_NetConfConfigFlowMod::MODIFY_FLOW;
}else if(!strcmp(command, "MODIFY_STRICT_FLOW")){
return OF_NetConfConfigFlowMod::MODIFY_STRICT_FLOW;
}else if(!strcmp(command, "DELETE_FLOW")){
return OF_NetConfConfigFlowMod::DELETE_FLOW;
}else if(!strcmp(command, "DELETE_STRICT_FLOW")){
return OF_NetConfConfigFlowMod::DELETE_STRICT_FLOW;
}else if(!strcmp(command, "NO_ACTION")){
return OF_NetConfConfigFlowMod::NO_ACTION;
}else{
throw cRuntimeError("OF_NetConfApplicationFlowMod: could not parse command attribute from XML");
}
}
}
| 2,865
|
C++
|
.cc
| 58
| 44.017241
| 121
| 0.731856
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,183
|
NetConfAppConfigParserSRPTable.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/srptable/NetConfAppConfigParserSRPTable.cc
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
//STD
#include <string>
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/srptable/NetConfAppConfigParserSRPTable.h>
#include <sdn4core/netconf/datastructures/srp/NetConfConfigSRP.h>
#include <core4inet/services/avb/SRP/SRPTable.h>
using namespace std;
namespace SDN4CoRE {
NetConfConfig* SDN4CoRE::NetConfAppConfigParserSRPTable::getConfigDataFor( cXMLElement* element) {
NetConfConfigSRP* configData = new NetConfConfigSRP();
cXMLElement* configsXML = element->getFirstChildWithTag("config");
for(cXMLElement* config: configsXML->getChildren()){
uint64_t streamID = atoi(config->getAttribute("stream_id"));
uint64_t vlanID = atoi(config->getAttribute("vlan_id"));
cModule* module = getSimulation()->getModuleByPath(config->getAttribute("module"));
string tagName = config->getTagName();
if( tagName == string("talkerEntry")){
CoRE4INET::SRPTable::TalkerEntry talker;
talker.streamId = streamID;
talker.vlan_id = vlanID;
talker.srClass = stringToEnum[string(config->getAttribute("srClass"))];
talker.address = inet::MACAddress(config->getAttribute("address"));
talker.module = module;
talker.framesize = atoi(config->getAttribute("framesize"));
talker.intervalFrames = atoi(config->getAttribute("intervalFrames"));
talker.pcp = atoi(config->getAttribute("pcp"));
configData->addTalkerEntry(talker);
}else if( tagName == string("listenerEntry")){
CoRE4INET::SRPTable::ListenerEntry listener;
listener.streamId = streamID;
listener.vlan_id = vlanID;
listener.module = module;
configData->addListenerEntry(listener);
}
}
return configData;
}
} /* namespace SDN4CoRE */
| 2,561
|
C++
|
.cc
| 54
| 41.611111
| 98
| 0.707982
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,184
|
NetConfAppConfigParserCollection.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserCollection.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "NetConfAppConfigParserCollection.h"
//STD
#include <algorithm>
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/openflow/NetConfAppConfigParserOpenFlow.h>
#include <sdn4core/netconf/applications/configparser/ieee8021qbv/NetConfAppConfigParserIEEE8021Qbv.h>
#include <sdn4core/netconf/applications/configparser/multipart/NetConfAppConfigParserMultipart.h>
#include <sdn4core/netconf/applications/configparser/srptable/NetConfAppConfigParserSRPTable.h>
#include <sdn4core/utility/xml/XMLUtility.h>
using namespace std;
namespace SDN4CoRE {
// All key strings have to be in lower case!!!
map<string, NetConfAppConfigParserBase*> NetConfAppConfigParserCollection::parsers =
{ {"ieee8021qbv", new NetConfAppConfigParserIEEE8021Qbv()},
{"openflow", new NetConfAppConfigParserOpenFlow()},
{"multipart", new NetConfAppConfigParserMultipart()},
{"srptable", new NetConfAppConfigParserSRPTable()}};
vector<Configuration_t*> NetConfAppConfigParserCollection::parseXMLConfigList(
const cXMLElementList& configuresXML, bool executionTimeRequired) {
vector<Configuration_t*> configurations;
for (auto configureXML : configuresXML) {
Configuration_t* config = parseXMLConfig(configureXML, executionTimeRequired);
if (config) {
configurations.push_back(config);
} else {
throw cRuntimeError(
"Could not parse XML input for Controller Application");
}
}
return configurations;
}
Configuration_t* NetConfAppConfigParserCollection::parseXMLConfig(
cXMLElement* configureXML, bool executionTimeRequired) {
Configuration_t* config = nullptr;
double executeAt = getDoubleAttributeFromXML(configureXML,"at",executionTimeRequired, SimTime::ZERO.dbl());
Configuration_t::NetConfMessageType_t configType =
static_cast<Configuration_t::NetConfMessageType_t> (Configuration_t::getConfigTypeFor(
getStringAttributeFromXML(configureXML, "type").c_str()));
if (configType >= 0) {
config = new Configuration_t();
config->executeAt = executeAt;
config->type = configType;
config->state =
Configuration_t::ConfigurationState_t::ConfigurationStateWaiting;
switch (config->type) {
case Configuration_t::NetConfMessageType_t::NetConfMessageType_EditConfig:
config->data = getConfigDataFor(configureXML);
config->filter = getConfigFilterFor(configureXML);
config->target = getStringAttributeFromXML(configureXML, "target", false, "running");
break;
case Configuration_t::NetConfMessageType_t::NetConfMessageType_GetConfig:
config->filter = getConfigFilterFor(configureXML);
config->target = getStringAttributeFromXML(configureXML, "target", false, "running");
break;
case Configuration_t::NetConfMessageType_t::NetConfMessageType_CopyConfig:
config->target = getStringAttributeFromXML(configureXML, "target", false, "candidate");
config->source = getStringAttributeFromXML(configureXML, "source", false, "running");
break;
case Configuration_t::NetConfMessageType_t::NetConfMessageType_DeleteConfig:
config->target = getStringAttributeFromXML(configureXML, "target");
break;
case Configuration_t::NetConfMessageType_t::NetConfMessageType_Lock:
config->target = getStringAttributeFromXML(configureXML, "target");
break;
case Configuration_t::NetConfMessageType_t::NetConfMessageType_Unlock:
config->target = getStringAttributeFromXML(configureXML, "target");
break;
default:
break;
}
}
return config;
}
NetConfConfig* NetConfAppConfigParserCollection::getConfigDataFor(
cXMLElement* element) {
NetConfConfig* config = nullptr;
const char* module = element->getAttribute("module");
if (module) {
string configType = module;
transform(configType.begin(), configType.end(), configType.begin(), ::tolower);
auto parser = parsers.find(configType);
if (parser != parsers.end()) {
config = parser->second->getConfigDataFor(element);
if (!config) {
throw cRuntimeError("Config parser %s returned null element", configType.c_str());
}
} else {
throw cRuntimeError("Unknown XML Parser type %s", configType.c_str());
}
} else {
config = new NetConfConfig();
}
return config;
}
NetConfFilter* NetConfAppConfigParserCollection::getConfigFilterFor(
cXMLElement* element) {
// NetConfFilter* filter = nullptr;
// const char* filterType = element->getAttribute("module");
// if (filterType) {
// auto parser = parsers.find(filterType);
// if (parser != parsers.end()) {
// filter = parser->second->getConfigFilterFor(element);
// if (!filter) {
// throw cRuntimeError("Filter parser %s returned null element", filterType);
// }
// } else {
// throw cRuntimeError("Unknown XML Parser type %s", filterType);
// }
// } else {
// filter = new NetConfFilter();
// }
return new NetConfFilter();
}
vector<NetConfApplicationBase::Connection_t> NetConfAppConfigParserCollection::parseXMLConnectionList(
const cXMLElementList& connectionsXML, bool executionTimeRequired) {
vector<NetConfApplicationBase::Connection_t> connections;
for (size_t i = 0; i < connectionsXML.size(); i++) {
connections.push_back(parseXMLConnection(connectionsXML[i], executionTimeRequired));
}
return connections;
}
NetConfApplicationBase::Connection_t NetConfAppConfigParserCollection::parseXMLConnection(
cXMLElement* element, bool executionTimeRequired) {
NetConfApplicationBase::Connection_t connection;
connection.localPort = getIntAttributeFromXML(element,"local_port");
connection.remoteAddress = getStringAttributeFromXML(element,"remote_address");
connection.remotePort = getIntAttributeFromXML(element,"remote_port");
connection.connectAt = getDoubleAttributeFromXML(element,"connect_at", executionTimeRequired, SimTime::ZERO.dbl());
connection.state = NetConfApplicationBase::ConnectionState_t::ConnectionStateWaiting;
// check if there are any configurations.
connection.configurations = parseXMLConfigList(element->getChildrenByTagName("configure"), executionTimeRequired);
return connection;
}
} // namespace SDN4CoRE
| 7,382
|
C++
|
.cc
| 150
| 42.92
| 119
| 0.712386
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,185
|
NetConfApplicationBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/applications/base/NetConfApplicationBase.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "NetConfApplicationBase.h"
//STD
#include <string>
//INET
#include "inet/networklayer/common/L3AddressResolver.h"
//SDN4CoRE
#include <sdn4core/netconf/applications/configparser/base/NetConfAppConfigParserCollection.h>
#include <sdn4core/utility/xml/XMLUtility.h>
namespace SDN4CoRE {
Define_Module(NetConfApplicationBase);
#define SELFMESSAGE_SEND_NETCONF "Send Netconf"
NetConfApplicationBase::~NetConfApplicationBase() {
for(auto conn : this->_connections){
for(auto config : conn.configurations){
delete config;
}
}
}
void NetConfApplicationBase::initialize() {
SimTime configStartOffset = par("configStartOffset");
cXMLElement* xmlServerConnections = par("serverConnections").xmlValue();
if (xmlServerConnections) {
if (strcmp(xmlServerConnections->getName(), "server_connections")
== 0) {
cXMLElementList applicationsXML =
xmlServerConnections->getChildrenByTagName("application");
for (size_t i = 0; i < applicationsXML.size(); i++) {
std::string clientAppHost = getStringAttributeFromXML(applicationsXML[i],"client_host");
int clientAppIndex = getIntAttributeFromXML(applicationsXML[i],"client_app");
const char* realHost = getParentModule()->getParentModule()->getFullName();
if (clientAppIndex == getIndex() && (strcmp(realHost, clientAppHost.c_str()) == 0)) {
auto connectionList = NetConfAppConfigParserCollection::parseXMLConnectionList(
applicationsXML[i]->getChildrenByTagName("connection"), true);
for(auto connection : connectionList) {
if(!configStartOffset.isZero()) {
for(auto config : connection.configurations) {
config->executeAt += configStartOffset;
}
}
_connections.push_back(connection);
}
}
}
}
}
WATCH_VECTOR(_connections);
bool scheduled = scheduleNextConnection();
if (getEnvir()->isGUI()) {
if(scheduled) {
getDisplayString().setTagArg("i2", 0, "status/asleep");
} else {
getDisplayString().setTagArg("i2", 0, "status/stop");
}
}
}
bool NetConfApplicationBase::scheduleNextConnection() {
bool scheduled = false;
int index = -1;
SimTime next = SimTime::getMaxTime();
for (size_t i = 0; i < _connections.size(); i++) {
auto connection = _connections[i];
if (connection.connectAt < next && connection.connectAt >= simTime()
&& (connection.state
== ConnectionState_t::ConnectionStateWaiting)) {
index = i;
next = connection.connectAt;
}
}
if (index > -1) {
_connections[index].state = ConnectionState_t::ConnectionStateScheduled;
cMessage* msg = new cMessage(SELFMESSAGE_SEND_HELLO);
msg->setContextPointer(&_connections[index]);
scheduleAt(next, msg);
scheduled = true;
}
return scheduled;
}
bool NetConfApplicationBase::scheduleNextConfigurationFor(
Connection_t* connection) {
bool scheduled = false;
if (connection
&& (connection->state
== ConnectionState_t::ConnectionStateEstablished)) {
int index = -1;
SimTime next = SimTime::getMaxTime();
for (size_t i = 0; i < connection->configurations.size(); i++) {
auto configuration = connection->configurations[i];
if (configuration->executeAt < next
&& configuration->executeAt >= simTime()
&& (configuration->state
== Configuration_t::ConfigurationState_t::ConfigurationStateWaiting)) {
index = i;
next = configuration->executeAt;
}
}
if (index > -1) {
NetConfMessage_RPC* rpc = createNetConfRPCForConfiguration(
connection, connection->configurations[index], std::to_string(index));
if (rpc) {
rpc->setContextPointer(connection);
cMessage* msg = new cMessage(SELFMESSAGE_SEND_NETCONF);
msg->setContextPointer(rpc);
scheduleAt(next, msg);
scheduled = true;
connection->configurations[index]->state =
Configuration_t::ConfigurationState_t::ConfigurationStateScheduled;
} else {
connection->configurations[index]->state =
Configuration_t::ConfigurationState_t::ConfigurationStateError;
}
}
}
return scheduled;
}
void NetConfApplicationBase::handleMessage(cMessage *msg) {
static int activeConnections = 0;
static int activeConfigurations = 0;
bool scheduled = false;
if (msg->isSelfMessage()) {
if (strcmp(msg->getName(), SELFMESSAGE_SEND_HELLO) == 0) {
Connection_t* connection =
static_cast<Connection_t*>(msg->getContextPointer());
if (connection) {
send(createHelloFor(connection), gate("applicationOut"));
connection->state = ConnectionState_t::ConnectionStateRequested;
activeConnections++;
if (getEnvir()->isGUI())
{
getDisplayString().setTagArg("i2", 0, "status/active");
}
}
scheduled = scheduleNextConnection();
} else if (strcmp(msg->getName(), SELFMESSAGE_SEND_NETCONF) == 0) {
NetConfMessage_RPC* rpc = static_cast<NetConfMessage_RPC*> (msg->getContextPointer());
if(rpc){
Connection_t* connection =
static_cast<Connection_t*>(rpc->getContextPointer());
NetConfCtrlInfo* ctrl = dynamic_cast<NetConfCtrlInfo*>(rpc->getControlInfo());
if(ctrl && connection){
connection->configurations[atoi(ctrl->getMessage_id())]->state = Configuration_t::ConfigurationState_t::ConfigurationStateRequested;
send(rpc, gate("applicationOut"));
activeConfigurations++;
scheduled = scheduleNextConfigurationFor(connection);
if(!scheduled) {
activeConnections--;
}
}
}
}
} else if (NetConfHello* hello = dynamic_cast<NetConfHello*>(msg)) {
NetConfClientSessionInfoTCP* sessionInfo =
(NetConfClientSessionInfoTCP*) hello->getContextPointer();
Connection_t* connection = mapSessionInfoToConnection(sessionInfo);
if (connection) {
connection->session_id = sessionInfo->getSessionId();
connection->state = ConnectionState_t::ConnectionStateEstablished;
scheduled = scheduleNextConfigurationFor(connection);
if(!scheduled) {
activeConnections--;
}
}
} else if (NetConfMessage_RPCReply* reply = dynamic_cast<NetConfMessage_RPCReply*>(msg)){
if(NetConfCtrlInfo* info = dynamic_cast<NetConfCtrlInfo*>(reply->getControlInfo())){
Connection_t* found = nullptr;
for (size_t i = 0; i < _connections.size(); i++) {
auto& connection = _connections[i];
if (connection.state
== ConnectionState_t::ConnectionStateEstablished
&& connection.session_id == info->getSession_id()) {
found = &connection;
}
}
if(found){
activeConfigurations--;
if(dynamic_cast<NetConf_RPCReplyElement_Ok*>(reply->getEncapsulatedPacket())){
found->configurations[atoi(info->getMessage_id())]->state = Configuration_t::ConfigurationState_t::ConfigurationStateSuccess;
} else if(dynamic_cast<NetConf_RPCReplyElement_Error*>(reply->getEncapsulatedPacket())) {
found->configurations[atoi(info->getMessage_id())]->state = Configuration_t::ConfigurationState_t::ConfigurationStateError;
}
}
}
}
if (getEnvir()->isGUI()) {
if(activeConfigurations + activeConnections > 0) {
//we are active
getDisplayString().setTagArg("i2", 0, "status/active");
} else if(scheduled) {
getDisplayString().setTagArg("i2", 0, "status/asleep");
} else {
getDisplayString().setTagArg("i2", 0, "status/check");
}
}
delete msg;
}
NetConfHello* NetConfApplicationBase::createHelloFor(
Connection_t* connection) {
NetConfHello* hello = new NetConfHello("NetConfHello");
NetConfClientCtrlInfo_Connection* ctrl =
new NetConfClientCtrlInfo_Connection();
ctrl->setConnectAddress(connection->remoteAddress.c_str());
ctrl->setConnectPort(connection->remotePort);
ctrl->setLocalPort(connection->localPort);
hello->setControlInfo(ctrl);
return hello;
}
NetConfOperation_EditConfig* NetConfApplicationBase::createEditConfigOperation(
Configuration_t* config) {
NetConfOperation_EditConfig* editconfig =
new NetConfOperation_EditConfig();
editconfig->setTarget(config->target.c_str());
editconfig->encapsulate(config->data->dup());
editconfig->setDefaultOperation(
NetConfOperation_Operation::NETCONFOPERATION_OPERATION_MERGE);
editconfig->setErrorOption(
NetConfOperation_ErrorOption::NETCONFOPERATION_ERROROPTION_CONTINUEONERROR);
editconfig->addByteLength(sizeof(editconfig->getTarget()));
return editconfig;
}
NetConfOperation_GetConfig* NetConfApplicationBase::createGetConfigOperation(
Configuration_t* config) {
NetConfOperation_GetConfig* getconfig =
new NetConfOperation_GetConfig();
getconfig->setSource(config->source.c_str());
getconfig->setFilter(*(config->filter));
getconfig->addByteLength(
sizeof(getconfig->getSource())
+ config->filter->getByteSize());
return getconfig;
}
NetConfOperation_CopyConfig* NetConfApplicationBase::createCopyConfigOperation(
Configuration_t* config) {
NetConfOperation_CopyConfig* copyconfig =
new NetConfOperation_CopyConfig();
copyconfig->setSource(config->source.c_str());
copyconfig->setTarget(config->target.c_str());
copyconfig->addByteLength(
sizeof(copyconfig->getSource())
+ sizeof(copyconfig->getTarget()));
return copyconfig;
}
NetConfOperation_DeleteConfig* NetConfApplicationBase::createDeleteConfigOperation(
Configuration_t* config) {
NetConfOperation_DeleteConfig* deleteconfig =
new NetConfOperation_DeleteConfig();
deleteconfig->setTarget(config->target.c_str());
deleteconfig->addByteLength(
sizeof(deleteconfig->getTarget()));
return deleteconfig;
}
NetConfOperation_Lock* NetConfApplicationBase::createLockOperation(
Configuration_t* config){
NetConfOperation_Lock* lock =
new NetConfOperation_Lock();
lock->setTarget(config->target.c_str());
lock->addByteLength(
sizeof(lock->getTarget()));
return lock;
}
NetConfOperation_Unlock* NetConfApplicationBase::createUnlockOperation(
Configuration_t* config){
NetConfOperation_Unlock* unlock =
new NetConfOperation_Unlock();
unlock->setTarget(config->target.c_str());
unlock->addByteLength(
sizeof(unlock->getTarget()));
return unlock;
}
NetConfOperation_Commit* NetConfApplicationBase::createCommitOperation(
Configuration_t* config){
NetConfOperation_Commit* commit =
new NetConfOperation_Commit();
return commit;
}
NetConfCtrlInfo* NetConfApplicationBase::createControlInfo(int messageType, int sessionId,
const char* messageId) {
NetConfCtrlInfo* ctrl = new NetConfCtrlInfo();
ctrl->setMessageType(messageType);
ctrl->setSession_id(sessionId);
ctrl->setMessage_id(messageId);
return ctrl;
}
NetConfMessage_RPC* NetConfApplicationBase::createNetConfRPCForConfiguration(
Connection_t* connection, Configuration_t* config, std::string message_id) {
NetConfMessage_RPC* rpc = new NetConfMessage_RPC();
rpc->setMessage_id(message_id.c_str());
rpc->addByteLength(
sizeof(rpc->getMessageType())
+ sizeof(rpc->getMessage_id()));
if (config) {
switch (config->type) {
case Configuration_t::NetConfMessageType_EditConfig:
rpc->setName("RPC EditConfig");
rpc->encapsulate(createEditConfigOperation(config));
break;
case Configuration_t::NetConfMessageType_GetConfig:
rpc->setName("RPC GetConfig");
rpc->encapsulate(createGetConfigOperation(config));
break;
case Configuration_t::NetConfMessageType_CopyConfig:
rpc->setName("RPC CopyConfig");
rpc->encapsulate(createCopyConfigOperation(config));
break;
case Configuration_t::NetConfMessageType_DeleteConfig:
rpc->setName("RPC DeleteConfig");
rpc->encapsulate(createDeleteConfigOperation(config));
break;
case Configuration_t::NetConfMessageType_Lock:
rpc->setName("RPC LockConfig");
rpc->encapsulate(createLockOperation(config));
break;
case Configuration_t::NetConfMessageType_Unlock:
rpc->setName("RPC UnlockConfig");
rpc->encapsulate(createUnlockOperation(config));
break;
case Configuration_t::NetConfMessageType_Commit:
rpc->setName("RPC CommitConfig");
rpc->encapsulate(createCommitOperation(config));
break;
default:
throw cRuntimeError("Can't create RPC for configuration: NetConfMessageType unknown.");
break;
}
}
rpc->setControlInfo(createControlInfo(rpc->getMessageType(), connection->session_id, rpc->getMessage_id()));
return rpc;
}
NetConfApplicationBase::Connection_t* NetConfApplicationBase::mapSessionInfoToConnection(
NetConfClientSessionInfoTCP* sessionInfo) {
if (sessionInfo) {
for (size_t i = 0; i < _connections.size(); i++) {
auto& connection = _connections[i];
if (connection.state
== ConnectionState_t::ConnectionStateEstablished
&& connection.session_id == sessionInfo->getSessionId()) {
return &connection;
}
//connection not yet established so use ip address
else if ((connection.session_id == -1)
&& (inet::L3AddressResolver().resolve(
connection.remoteAddress.c_str()).str() ==
sessionInfo->getSocket()->getRemoteAddress().str())) {
return &connection;
}
}
}
return nullptr;
}
void NetConfApplicationBase::setConnnections(std::vector<NetConfApplicationBase::Connection_t>& connections){
Enter_Method_Silent();
_connections.clear();
for(Connection_t& connection: connections){
for(Configuration_t* configuration: connection.configurations){
this->take(configuration->data);
}
_connections.push_back(connection);
}
}
} // namespace SDN4CoRE
| 16,562
|
C++
|
.cc
| 374
| 33.836898
| 152
| 0.62671
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,186
|
NetConfClientTCP.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/client/tcp/NetConfClientTCP.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/netconf/client/tcp/NetConfClientTCP.h>
#include <sdn4core/netconf/datastructures/tcp/NetConfClientSessionInfoTCP.h>
#include "inet/networklayer/common/L3AddressResolver.h"
using namespace inet;
namespace SDN4CoRE {
Define_Module(NetConfClientTCP);
void NetConfClientTCP::initialize()
{
NetConfClientBase::initialize();
}
void NetConfClientTCP::handleMessage(cMessage* msg) {
if(msg->getKind() == TCP_I_ESTABLISHED){
NetConfClientSessionInfoTCP* sessionInfo = dynamic_cast<NetConfClientSessionInfoTCP*>(findSessionInfoForMsg(msg));
sessionInfo->getSocket()->processMessage(msg);
}else{
NetConfClientBase::handleMessage(msg);
}
}
void NetConfClientTCP::sendToTransport(cMessage* msg) {// Detach control info and use it for forwarding
NetConfCtrlInfo* ctrl = dynamic_cast<NetConfCtrlInfo*>(msg->removeControlInfo());
// get session info
NetConfClientSessionInfoTCP* sessionInfo = dynamic_cast<NetConfClientSessionInfoTCP*>(findSessionInfoForId(ctrl->getSession_id()));
// forward to tcp
sessionInfo->getSocket()->send(msg);
// delete control info
delete ctrl;
}
NetConfClientSessionInfo* NetConfClientTCP::openNewSession(NetConfHello* hello) {
NetConfClientCtrlInfo_Connection* ctrl = dynamic_cast<NetConfClientCtrlInfo_Connection*>(hello->removeControlInfo());
NetConfClientSessionInfoTCP* sessionInfo = nullptr;
if(ctrl){
// create new socket
TCPSocket *socket = new TCPSocket();
socket->setOutputGate(gate(TRANSPORT_OUT_GATE_NAME));
socket->setDataTransferMode(TCP_TRANSFER_OBJECT);
socket->bind(ctrl->getLocalPort());
sessionInfo = new NetConfClientSessionInfoTCP();
sessionInfo->setSocket(socket);
sessionInfo->setConnId(socket->getConnectionId());
// insert into open sessions
_openSessions.push_back(sessionInfo);
// connect to the other socket.
socket->connect(L3AddressResolver().resolve(ctrl->getConnectAddress()), ctrl->getConnectPort());
// send the hello directly
socket->send(hello);
}
delete ctrl;
return dynamic_cast<NetConfClientSessionInfo*>(sessionInfo);
}
bool NetConfClientTCP::closeSession(int sessionId) {
NetConfClientSessionInfoTCP* sessionInfo = dynamic_cast<NetConfClientSessionInfoTCP*>(findSessionInfoForId(sessionId));
if(!sessionInfo){
// close socket
sessionInfo->getSocket()->close();
// delete from open sessions
for(auto i=_openSessions.begin(); i != _openSessions.end(); ++i) {
if((*i)->getSessionId() == sessionInfo->getSessionId()){
_openSessions.erase(i);
}
}
return true;
}
return false;
}
NetConfClientSessionInfo* NetConfClientTCP::findSessionInfoForMsg(cMessage* msg) {
TCPCommand *ind = dynamic_cast<TCPCommand *>(msg->getControlInfo());
if (!ind)
throw cRuntimeError("TCPSocketMap: findSocketFor(): no TCPCommand control info in message (not from TCP?)");
int connId = ind->getConnId();
for(auto i=_openSessions.begin(); i != _openSessions.end(); ++i) {
NetConfClientSessionInfoTCP* sessionInfo = dynamic_cast<NetConfClientSessionInfoTCP*>(*i);
if(sessionInfo->getConnId() == connId){
return sessionInfo;
}
}
return NULL;
}
} // namespace SDN4CoRE
| 4,125
|
C++
|
.cc
| 94
| 38.56383
| 135
| 0.722097
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,187
|
NetConfClientBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/client/base/NetConfClientBase.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "NetConfClientBase.h"
namespace SDN4CoRE {
const char NetConfClientBase::APPLICATION_OUT_GATE_NAME[] = "applicationOut";
const char NetConfClientBase::APPLICATION_IN_GATE_NAME[] = "applicationIn";
const char NetConfClientBase::TRANSPORT_IN_GATE_NAME[] = "transportIn";
const char NetConfClientBase::TRANSPORT_OUT_GATE_NAME[] = "transportOut";
void NetConfClientBase::initialize()
{
// Nothing to initialize?
}
void NetConfClientBase::handleMessage(cMessage *msg)
{
if(msg->arrivedOn(APPLICATION_IN_GATE_NAME)){
if (NetConfHello* hello = dynamic_cast<NetConfHello*>(msg)) {
// received hello
sendHello(hello);
} else if (dynamic_cast<NetConfMessage*>(msg)){
sendToTransport(msg);
} else {
throw cRuntimeError("Received message of unknown type from application.");
}
} else if (msg->arrivedOn(TRANSPORT_IN_GATE_NAME)){
if (NetConfHello* hello = dynamic_cast<NetConfHello*>(msg)) {
// received hello
handleHello(hello);
} else if (NetConfMessage* netconf = dynamic_cast<NetConfMessage*>(msg)){
NetConfClientSessionInfo* sessionInfo = findSessionInfoForMsg(msg);
if(sessionInfo) {
// create control info
netconf->removeControlInfo();
netconf->setControlInfo(createCtrlInfoFor(sessionInfo,netconf));
//check for mesage type
switch(netconf->getMessageType()){
case NetConfMessageType::NETCONFMESSAGETYPE_RPCREPLY:
// received RPC
send(msg,this->gate(APPLICATION_OUT_GATE_NAME, sessionInfo->getApplicationIndex()));
break;
default:
throw cRuntimeError("Received NetConfMessage but its not Hello or RPCReply");
break;
}
} else {
throw cRuntimeError("Received NetConfMessage but there is no session for it.");
}
}
}
}
void NetConfClientBase::sendHello(NetConfHello* hello) {
int appIndex = hello->getArrivalGate()->getIndex();
NetConfClientSessionInfo* sessionInfo = openNewSession(hello);
sessionInfo->setApplicationIndex(appIndex);
}
void NetConfClientBase::handleHello(NetConfHello* hello) {
// received hello so open a new session
NetConfClientSessionInfo* sessionInfo = findSessionInfoForMsg(hello);
if(sessionInfo){
sessionInfo->setSessionId(hello->getSession_id());
}
hello->setContextPointer(sessionInfo);
send(hello,this->gate(APPLICATION_OUT_GATE_NAME, sessionInfo->getApplicationIndex()));
}
NetConfClientSessionInfo* NetConfClientBase::findSessionInfoForId(
int sessionId) {
for(auto i=_openSessions.begin(); i != _openSessions.end(); ++i) {
if((*i)->getSessionId() == sessionId){
return (*i);
}
}
return NULL;
}
NetConfCtrlInfo* NetConfClientBase::createCtrlInfoFor(
NetConfClientSessionInfo* sessionInfo, NetConfMessage* msg) {
// create control info
NetConfCtrlInfo* ctrl = new NetConfCtrlInfo();
ctrl->setMessageType(msg->getMessageType());
ctrl->setSession_id(sessionInfo->getSessionId());
if(NetConfMessage_RPC* rpc = dynamic_cast<NetConfMessage_RPC*>(msg)){
ctrl->setMessage_id(rpc->getMessage_id());
} else if (NetConfMessage_RPCReply* rpc = dynamic_cast<NetConfMessage_RPCReply*>(msg)){
ctrl->setMessage_id(rpc->getMessage_id());
}
return ctrl;
}
} // namespace SDN4CoRE
| 4,309
|
C++
|
.cc
| 100
| 36.02
| 104
| 0.679475
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,188
|
TSN_OF_SwitchAgent.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/tsn/engine/TSN_OF_SwitchAgent.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Tobias Haugg, for HAW Hamburg
#include <sdn4core/switch/tsn/engine/TSN_OF_SwitchAgent.h>
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/contract/ExtendedIeee802Ctrl_m.h"
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/messages/OFP_Packet_Out_m.h"
using namespace std;
using namespace inet;
using namespace openflow;
using namespace omnetpp;
namespace SDN4CoRE{
Define_Module(TSN_OF_SwitchAgent);
void TSN_OF_SwitchAgent::handleMessage(cMessage *msg){
if (msg->arrivedOn("srpIn")) {
if(CoRE4INET::ListenerReady* srp = dynamic_cast<CoRE4INET::ListenerReady *>(msg)){
sendSRPResponse(srp);
} else {
delete msg;
}
} else {
// nothing to do here - just forward
OF_SwitchAgent::handleMessage(msg);
}
}
void TSN_OF_SwitchAgent::sendSRPResponse(CoRE4INET::ListenerReady *msg){
OFP_Packet_In *packetIn = new OFP_Packet_In("packetIn");
ofp_header header = packetIn->getHeader();
header.version = OFP_VERSION;
header.type = OFPT_VENDOR;
packetIn->setHeader(header);
packetIn->setByteLength(32);
packetIn->encapsulate(msg);
packetIn->setBuffer_id(OFP_NO_BUFFER);
socket.send(packetIn);
}
void TSN_OF_SwitchAgent::processControlPlanePacket(cMessage *msg){
if (Open_Flow_Message *of_msg = dynamic_cast<Open_Flow_Message *>(msg)) { //msg from controller
ofp_type type = (ofp_type)of_msg->getHeader().type;
switch (type){
case OFPT_VENDOR:
controlPlanePacket++;
handleSRPFromController(of_msg);
break;
default:
//not a special OF message, forward to base class.
OF_SwitchAgent::processControlPlanePacket(msg);
break;
}
}
}
void TSN_OF_SwitchAgent::handleSRPFromController(cMessage* msg) {
if (OFP_Packet_Out *packetOut = dynamic_cast<OFP_Packet_Out *>(msg)) {
if (CoRE4INET::SRPFrame * srpFrame =
dynamic_cast<CoRE4INET::SRPFrame *>(packetOut->decapsulate())) {
inet::Ieee802Ctrl *etherctrl = new inet::Ieee802Ctrl();
etherctrl->setSwitchPort(packetOut->getIn_port());
//pack message
srpFrame->setControlInfo(etherctrl);
//forward to port
send(srpFrame, "srpOut");
} else {
throw cRuntimeError("SRP packet from controller received without Ieee802Ctrl");
}
}
delete msg;
}
}
| 3,224
|
C++
|
.cc
| 82
| 33.743902
| 99
| 0.691669
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,189
|
AVB_OF_SwitchAgent.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/engine/AVB_OF_SwitchAgent.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
//SND4CoRE
#include <sdn4core/switch/avb/engine/AVB_OF_SwitchAgent.h>
//STD
#include <sstream>
#include <string>
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//AUTO_GENERATED MESSAGES
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/contract/ExtendedIeee802Ctrl_m.h"
//openflow
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/messages/OFP_Packet_Out_m.h"
using namespace std;
using namespace inet;
using namespace openflow;
using namespace omnetpp;
namespace SDN4CoRE{
Define_Module(AVB_OF_SwitchAgent);
AVB_OF_SwitchAgent::AVB_OF_SwitchAgent() {}
AVB_OF_SwitchAgent::~AVB_OF_SwitchAgent() {}
void AVB_OF_SwitchAgent::forwardSRPtoController(cPacket* msg)
{
//TODO use experimenter Message for srp forwarding. Maybe add a custom reason.
OFP_Packet_In *packetIn = new OFP_Packet_In("packetIn");
ofp_header header = packetIn->getHeader();
header.version = OFP_VERSION;
header.type = OFPT_PACKET_IN;
packetIn->setHeader(header);
#if OFP_VERSION_IN_USE == OFP_100
packetIn->setReason(OFPR_NO_MATCH);//TODO maybe add another reason for realtime streams.
#elif OFP_VERSION_IN_USE == OFP_151
packetIn->setReason(OFPR_ACTION_SET);//TODO maybe add another reason for realtime streams.
#endif
packetIn->setByteLength(32);
if (inet::Ieee802Ctrl * controlInfo = dynamic_cast<inet::Ieee802Ctrl *>(msg->getControlInfo()))
{
oxm_basic_match match;
match.OFB_IN_PORT = controlInfo->getSwitchPort();
packetIn->setMatch(match);
}
// allways send full packet with packet-in message
packetIn->encapsulate(msg->dup());
packetIn->setBuffer_id(OFP_NO_BUFFER);
socket.send(packetIn);
}
void AVB_OF_SwitchAgent::initialize(int stage)
{
OF_SwitchAgent::initialize(stage);
switch (stage)
{
case INITSTAGE_LOCAL:
{
//register signals
forwardSRPtoConSig = registerSignal("forwardSRPtoConSig");
relayUnit->subscribe(forwardSRPtoConSig, this);
//load srp table module
_srpTable = dynamic_cast<CoRE4INET::SRPTable*> (getModuleByPath(par("srpTable")));
if (!_srpTable)
{
throw cRuntimeError("AVB_OF_SwitchAgent: Could not init as no SRP Table could be found at %s", par("srpTable").stringValue());
}
break;
}
case INITSTAGE_APPLICATION_LAYER:
{
//load XML config if specified.
cXMLElement* xmlDoc = par("configXML").xmlValue();
if(xmlDoc)
{
if(strcmp(xmlDoc->getName(), "config") == 0)
{
string switchName = getParentModule()->getSubmodule("eth", 0)->getSubmodule("mac")->par("address").stringValue();
if(cXMLElement* switchConfigXML = xmlDoc->getFirstChildWithAttribute("switch", "id", switchName.c_str()))
{//there is a config for this switch.
if(cXMLElement* srpTableXML = switchConfigXML->getFirstChildWithTag("srpTable"))
{//the config contains an srp table so set it.
if(_srpTable)
{
_srpTable->importFromXML(srpTableXML);
}
}
}
}
}
break;
}
default:
break;
}
}
void AVB_OF_SwitchAgent::handleMessage(cMessage *msg)
{
if (msg->arrivedOn("srpIn"))
{
((AVB_OF_RelayUnit*)relayUnit)->handleSRPFromProtocol(msg);
delete msg;
}
else
{ // nothing to do here - just forward
OF_SwitchAgent::handleMessage(msg);
}
}
void AVB_OF_SwitchAgent::handleSRPFromController(cMessage* msg)
{
if (OFP_Packet_Out *packetOut = dynamic_cast<OFP_Packet_Out *>(msg))
{
if (CoRE4INET::SRPFrame * srpFrame =
dynamic_cast<CoRE4INET::SRPFrame *>(packetOut->decapsulate()))
{
inet::Ieee802Ctrl *etherctrl = new inet::Ieee802Ctrl();
etherctrl->setSwitchPort(packetOut->getIn_port());
//pack message
srpFrame->setControlInfo(etherctrl);
//forward to port
send(srpFrame, "srpOut");
}
else
{
throw cRuntimeError("SRP packet from controller received without Ieee802Ctrl");
}
}
delete msg;
}
void AVB_OF_SwitchAgent::processControlPlanePacket(cMessage *msg)
{
if (Open_Flow_Message *of_msg = dynamic_cast<Open_Flow_Message *>(msg))
{ //msg from controller
ofp_type type = (ofp_type)of_msg->getHeader().type;
switch (type)
{
// TODO Add Experimenter Message Structure!
#if OFP_VERSION_IN_USE == OFP_100
case OFPT_VENDOR:
controlPlanePacket++;
handleSRPFromController(of_msg);
break;
#elif OFP_VERSION_IN_USE == OFP_151
case OFPT_EXPERIMENTER:
controlPlanePacket++;
handleSRPFromController(of_msg);
break;
#endif
default:
//not a special of message forward to base class.
OF_SwitchAgent::processControlPlanePacket(msg);
break;
}
}
}
void AVB_OF_SwitchAgent::receiveSignal(cComponent *src, simsignal_t id, cObject *value, cObject *details)
{
if (this->isConnectedToController())
{
if (id == forwardSRPtoConSig)
{
Enter_Method_Silent();
CoRE4INET::SRPFrame* toController = dynamic_cast<CoRE4INET::SRPFrame *>(value);
forwardSRPtoController(toController);
}
else
{
OF_SwitchAgent::receiveSignal(src, id, value, details);
}
}
}
} /*end namespace SDN4CoRE*/
| 6,597
|
C++
|
.cc
| 184
| 28.320652
| 142
| 0.635667
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,190
|
AVB_OF_RelayUnit.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/engine/AVB_OF_RelayUnit.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
//SDN4CoRE
#include <sdn4core/switch/avb/engine/AVB_OF_RelayUnit.h>
//STD
#include <sstream>
#include <string>
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//AUTO_GENERATED MESSAGES
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/contract/ExtendedIeee802Ctrl_m.h"
//openflow
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/messages/OFP_Packet_Out_m.h"
using namespace std;
using namespace inet;
using namespace openflow;
using namespace omnetpp;
namespace SDN4CoRE{
Define_Module(AVB_OF_RelayUnit);
AVB_OF_RelayUnit::AVB_OF_RelayUnit() {}
AVB_OF_RelayUnit::~AVB_OF_RelayUnit() {}
void AVB_OF_RelayUnit::initialize(int stage)
{
OF_RelayUnit::initialize(stage);
switch(stage){
case INITSTAGE_LOCAL:
{
//register siganls
forwardSRPtoConSig = registerSignal("forwardSRPtoConSig");
//load srp table module
_srpTable = dynamic_cast<CoRE4INET::SRPTable*> (getModuleByPath(par("srpTable")));
if (!_srpTable)
{
throw cRuntimeError("AVB_OF_SwitchAgent: Could not init as no SRP Table could be found at %s", par("srpTable").stringValue());
}
break;
}
case INITSTAGE_APPLICATION_LAYER:
{
//load XML config if specified.
cXMLElement* xmlDoc = par("configXML").xmlValue();
if (xmlDoc)
{
if (strcmp(xmlDoc->getName(), "config") == 0)
{
string switchName = getParentModule()->getSubmodule("eth", 0)->getSubmodule("mac")->par("address").stringValue();
if (cXMLElement* switchConfigXML = xmlDoc->getFirstChildWithAttribute("switch", "id", switchName.c_str()))
{//there is a config for this switch.
if (cXMLElement* srpTableXML = switchConfigXML->getFirstChildWithTag("srpTable"))
{//the config contains an srp table so set it.
if (_srpTable)
{
_srpTable->importFromXML(srpTableXML);
}
}
}
}
}
break;
}
default:
break;
}
}
void AVB_OF_RelayUnit::processDataPlanePacket(cMessage *msg)
{
if (isSRPMessage(msg))
{
dataPlanePacket++;
//forward to controller
CoRE4INET::SRPFrame* toController = dynamic_cast<CoRE4INET::SRPFrame *>(msg->dup());
inet::Ieee802Ctrl * controlInfo = new inet::Ieee802Ctrl();
controlInfo->setSwitchPort(msg->getArrivalGate()->getIndex());
toController->setControlInfo(controlInfo);
emit(forwardSRPtoConSig,toController);
delete toController;
}
else
{
OF_RelayUnit::processDataPlanePacket(msg);
}
}
openflow::oxm_basic_match AVB_OF_RelayUnit::extractMatch(
inet::EthernetIIFrame* frame)
{
oxm_basic_match match = OF_RelayUnit::extractMatch(frame);
if(match.OFB_ETH_TYPE == 0x8100)
{ //we have a q frame!
CoRE4INET::EthernetIIFrameWithQTag* qFrame =
dynamic_cast<CoRE4INET::EthernetIIFrameWithQTag*>(frame);
match.OFB_VLAN_VID = qFrame->getVID();
match.OFB_VLAN_PCP = qFrame->getPcp();
}
return match;
}
void AVB_OF_RelayUnit::handleSRPFromProtocol(cMessage* msg)
{
Enter_Method("handleSRPFromProtocol");
cObject* ctrlInfo = msg->removeControlInfo();
//check the control info and change it for the of-switch module.
if (CoRE4INET::ExtendedIeee802Ctrl *etherctrl =
dynamic_cast<CoRE4INET::ExtendedIeee802Ctrl *>(ctrlInfo))
{
//check for srp message type
if (dynamic_cast<CoRE4INET::TalkerAdvertise *>(msg))
{ //TalkerAdvertise
for (size_t i = 0; i < portVector.size(); ++i) {
if(i != etherctrl->getNotSwitchPort()) {
//pack message
cMessage* copy = msg->dup();
copy->setControlInfo(etherctrl->dup());
send(copy, "dataPlaneOut", i);
}
}
}
else if (dynamic_cast<CoRE4INET::ListenerReady *>(msg))
{ //check for srp message type
//pack message
cMessage* copy = msg->dup();
copy->setControlInfo(etherctrl->dup());
send(copy, "dataPlaneOut", etherctrl->getSwitchPort());
}
} else
{
throw cRuntimeError("Packet from SRP received without ExtendedIeee802Ctrl");
}
delete ctrlInfo;
}
bool AVB_OF_RelayUnit::isSRPMessage(cMessage* msg)
{
return msg->arrivedOn("srpIn") || dynamic_cast<CoRE4INET::SRPFrame *>(msg);
}
void AVB_OF_RelayUnit::finish()
{
// record statistics
recordScalar("packetsDataPlane", dataPlanePacket);
recordScalar("flowTableHit", flowTableHit);
recordScalar("flowTableMiss", flowTableMiss);
//print flow table
//xml head
std::ostringstream oss;
oss << "<config>" << endl;
oss << "<switch id=\"" << getParentModule()->getSubmodule("eth", 0)->getSubmodule("mac")->par("address").stringValue() << "\">" << endl;
for (size_t i = 0; i < _flowTables.size() ; i++)
{
oss << _flowTables[i]->exportToXML();
}
oss << _srpTable->exportToXML();
oss << "</switch>" << endl;
oss << "</config>" << endl;
cout << oss.str();
}
} /*end namespace SDN4CoRE*/
| 6,286
|
C++
|
.cc
| 170
| 29.341176
| 142
| 0.623074
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,191
|
AVBEthernetInterfaceConnection.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/port/AVBEthernetInterfaceConnection.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/switch/avb/port/AVBEthernetInterfaceConnection.h>
//STD
#include <iostream>
#include <list>
//CoRE4INET
#include "core4inet/buffer/AS6802/CTBuffer.h"
#include "core4inet/incoming/base/Incoming.h"
#include "core4inet/linklayer/ethernet/AS6802/CTFrame.h"
//Auto-generated Messages
#include "inet/linklayer/ethernet/EtherFrame_m.h"
#include "core4inet/linklayer/contract/ExtendedIeee802Ctrl_m.h"
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
using namespace CoRE4INET;
using namespace omnetpp;
namespace SDN4CoRE{
Define_Module(AVBEthernetInterfaceConnection);
void AVBEthernetInterfaceConnection::initialize()
{
CTApplicationBase::initialize();
_avbOutCTC = getParentModule()->getSubmodule("avbCTC");
_beBuffer = getParentModule()->getSubmodule("bgOut");
//set port info
_portNo = getParentModule()->getIndex();
_portCount = getParentModule()->getVectorSize();
}
bool AVBEthernetInterfaceConnection::isSRPMessage(cMessage* msg) {
return msg->arrivedOn("encapSrpIn") || dynamic_cast<CoRE4INET::SRPFrame *>(msg);
}
void AVBEthernetInterfaceConnection::handleMessage(cMessage *msg)
{
CTApplicationBase::handleMessage(msg);
EV_INFO << "RTEtherPort received a message: " << msg << endl;
if (isSRPMessage(msg)) {
// srp message --> forward to correct modules
handleSRPMessage(msg);
} else if(msg->arrivedOn("upperLayerIn")){
//from switch --> forward to correct buffer
handleOutMessage(msg);
} else {
//this message should be forwarded to the upper layer!
handleSwitchMessage(msg);
}
delete msg;
}
void AVBEthernetInterfaceConnection::handleSRPMessage(cMessage* msg) {
// srp message --> forward to correct modules
if (msg->arrivedOn("encapSrpIn")) {//from encap to controller
//check the control info and change it for the of-switch module.
inet::Ieee802Ctrl *etherctrl = dynamic_cast<inet::Ieee802Ctrl *>(msg->removeControlInfo());
if (!etherctrl)
{
error("packet `%s' from encap received without Ieee802Ctrl", msg->getName());
}
else
{
//set correct port number
etherctrl->setSwitchPort(_portNo);
//pack message
cMessage* fromEncap = msg->dup();
fromEncap->setControlInfo(etherctrl);
send(fromEncap, "upperLayerOut");
}
} else if (msg->arrivedOn("upperLayerIn")) {//from controller to encap
// srp message --> forward to correct modules
if (CoRE4INET::ExtendedIeee802Ctrl *etherctrl = dynamic_cast<CoRE4INET::ExtendedIeee802Ctrl *>(msg->removeControlInfo())) { //ExtendedIeee802Ctrl --> encap
//manipulate port to 0 because the port thinks he is a host.
if(etherctrl->getSwitchPort() == SWITCH_PORT_BROADCAST) {
if(etherctrl->getNotSwitchPort() == this->_portNo) {
//do not broadcast it.
etherctrl->setNotSwitchPort(0);
} else {
//set to other port than 0 to not ignore it.
etherctrl->setNotSwitchPort(1);
}
} else if (etherctrl->getSwitchPort() == this->_portNo) {
etherctrl->setSwitchPort(0);
} else {
etherctrl->setSwitchPort(1);
}
//pack message
cMessage* deliver = msg->dup();
deliver->setControlInfo(etherctrl);
send(deliver, "encapSrpOut");
} else {
error("packet `%s' from upperLayer received without Ieee802Ctrl",
msg->getName());
}
} else {
error("SRP packet `%s' received on wrong gate", msg->getName());
}
}
void AVBEthernetInterfaceConnection::handleSwitchMessage(cMessage* msg) {
//this message should be forwarded to the upper layer!
EV_INFO << "Forwarding to upperLayer.\n";
send(msg->dup(), "upperLayerOut");
}
void AVBEthernetInterfaceConnection::handleOutMessage(cMessage* msg) {
//from switch --> forward to correct buffer
if(AVBFrame* avbFrame = dynamic_cast<AVBFrame*>(msg)){
EV_INFO << "Treated as AVB --> forward to avbCTC." << endl;
//get sender module to forward input.
//const char * name = msg->getSenderModule()->getName();
//AVB transfer
sendDirect(avbFrame->dup(), _avbOutCTC->gate("in"));
}else if(CTFrame* ctFrame = dynamic_cast<CTFrame*>(msg)){
EV_INFO << "Treated as ct";
//ct frame so find correct buffer virtual link
std::list<CoRE4INET::CTBuffer*> buffer = ctbuffers[ctFrame->getCtID()];
for(std::list<CoRE4INET::CTBuffer*>::iterator buf = buffer.begin(); buf!=buffer.end(); ++buf){
EV_INFO << " --> forward to virtual link buffer." << endl;
Incoming *in = dynamic_cast<Incoming *>((*buf)->gate("in")->getPathStartGate()->getOwner());
sendDirect(ctFrame->dup(), in->gate("in"));
}
}else if(inet::EthernetIIFrame* ethernetFrame = dynamic_cast<inet::EthernetIIFrame*>(msg)){
EV_INFO << "Treated as BE --> forward to best effort buffer." << endl;
//BE transfer
sendDirect(ethernetFrame->dup(), _beBuffer->gate("in"));
//for (std::list<BGBuffer*>::iterator buf = bgbuffers.begin(); buf != bgbuffers.end(); ++buf) {
// sendDirect(ethernetFrame->dup(), (*buf)->gate("in"));
//}
}
}
} /*end namespace SDN4CoRE*/
| 6,257
|
C++
|
.cc
| 140
| 37.685714
| 163
| 0.657302
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,192
|
OF_AVBIncoming.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/avb/incoming/avb/OF_AVBIncoming.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/switch/avb/incoming/avb/OF_AVBIncoming.h>
//STD
#include <list>
#include <string>
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//CoRE4INET auto-generated
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
//INET
#include "inet/common/ModuleAccess.h"
using namespace std;
using namespace CoRE4INET;
namespace SDN4CoRE {
Define_Module(OF_AVBIncoming);
OF_AVBIncoming::OF_AVBIncoming() {
this->srptable = nullptr;
}
void OF_AVBIncoming::initialize() {
this->srptable = inet::getModuleFromPar<SRPTable>(par("srpTable"), this,
true);
if (!srptable) {
throw cRuntimeError(
"Cannot find module srpTable in node. srpTable is required");
}
}
void OF_AVBIncoming::handleMessage(cMessage* msg) {
if (msg && msg->arrivedOn("in")) {
if (AVBFrame *inFrame = dynamic_cast<AVBFrame*>(msg)) {
//get sender module to forward input.
const char * name = msg->getSenderModule()->getName();
if (strcmp(name, "inControl") == 0) {
//forward to gateway module
send(inFrame->dup(),"toGateway");
} else {
std::list<cModule*> listeners =
srptable->getListenersForTalkerAddress(
inFrame->getDest(), inFrame->getVID());
SR_CLASS srClass = srptable->getSrClassForTalkerAddress(
inFrame->getDest(), inFrame->getVID());
if (listeners.empty()) {
emit(droppedSignal, inFrame);
} else {
for (std::list<cModule*>::const_iterator listener =
listeners.begin(); listener != listeners.end();
++listener) {
if ((*listener) == this->getParentModule()) {
if (((*listener)->getSubmodule("phy") != nullptr)
|| ((*listener)->getSubmodule("phy",0) != nullptr))
{
string outputStr;
if (srClass == SR_CLASS::A)
outputStr = "AVBAout";
else if (srClass == SR_CLASS::B)
outputStr = "AVBBout";
sendDelayed(inFrame->dup(), getHardwareDelay(),
gate(outputStr.c_str(), 0));
emit(rxPkSignal, inFrame);
} else {
if ((*listener)->hasGate("AVBin")) {
sendDirect(inFrame->dup(),
(*listener)->gate("AVBin"));
emit(rxPkSignal, inFrame);
}
if ((*listener)->hasGate("AVBin",0)) {
sendDirect(inFrame->dup(),
(*listener)->gate("AVBin",0));
emit(rxPkSignal, inFrame);
}
}
}
}
}
}
delete inFrame;
} else {
throw cRuntimeError("Received non-AVBFrame frame");
}
} else {
delete msg;
}
}
} /* namespace SDN4CoRE */
| 4,196
|
C++
|
.cc
| 98
| 28.204082
| 87
| 0.501592
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,193
|
OF_RelayUnit.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/base/engine/OF_RelayUnit.cc
|
//STD
#include <sstream>
#include <string>
//inet
#include "inet/linklayer/ethernet/EtherMACBase.h"
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/networklayer/common/L3AddressResolver.h"
#include "inet/transportlayer/contract/ITransportPacket.h"
#include "inet/common/ModuleAccess.h"
#include "inet/networklayer/common/InterfaceTable.h"
#include "inet/networklayer/ipv4/ICMPMessage.h"
//Auto-generated Messages
#include "inet/networklayer/arp/ipv4/ARPPacket_m.h"
#include "inet/applications/pingapp/PingPayload_m.h"
//openflow
#include <openflow/openflow/protocol/OpenFlow.h>
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/messages/Open_Flow_Message_m.h"
#include "openflow/messages/OFP_Features_Reply_m.h"
#include "openflow/messages/OFP_Hello_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/messages/OFP_Packet_Out_m.h"
#include "openflow/messages/OFP_Flow_Mod_m.h"
//CoRE4INET
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
//SDN4CoRE
#include <sdn4core/switch/base/engine/OF_SwitchAgent.h>
#include <sdn4core/switch/base/engine/OF_RelayUnit.h>
using namespace std;
using namespace inet;
using namespace openflow;
namespace SDN4CoRE{
Define_Module(OF_RelayUnit);
OF_RelayUnit::OF_RelayUnit() {}
OF_RelayUnit::~OF_RelayUnit() {}
void OF_RelayUnit::initialize(int stage)
{
switch(stage)
{
case INITSTAGE_LOCAL:
{
//stats
dpPingPacketHash = registerSignal("dpPingPacketHash");
cpPingPacketHash = registerSignal("cpPingPacketHash");
forwardToConSign = registerSignal("forwardToConSign");
tableMissSign = registerSignal("tableMissSign");
dataPlanePacket=0l;
flowTableHit=0l;
flowTableMiss=0l;
//load table modules.
int numFlowTables = getParentModule()->getSubmodule("flowTables",0)->getVectorSize();
for (int i = 0; i < numFlowTables; i++)
{
if(OF_FlowTable* table = dynamic_cast<OF_FlowTable*> (getParentModule()->getSubmodule("flowTables",i)))
{
_flowTables.push_back(table);
}
}
break;
}
case INITSTAGE_NETWORK_LAYER:
{ // Init all ports
portVector.resize(gateSize("dataPlaneIn"));
for (unsigned int i=0;i<portVector.size();i++)
{
portVector[i].port_no = i+1;
cModule *ethernetModule = gate("dataPlaneOut",i)->getNextGate()->getOwnerModule()->getSubmodule("mac");
if (dynamic_cast<EtherMACBase *>(ethernetModule) != NULL)
{
EtherMACBase *nic = (EtherMACBase *)ethernetModule;
uint64_t tmpHw = nic->getMACAddress().getInt();
memcpy(portVector[i].hw_addr,&tmpHw, sizeof tmpHw);
}
sprintf(portVector[i].name,"Port: %d",i);
portVector[i].config =0;
portVector[i].state =0;
//TODO fix wildcards for OFP151!
#if OFP_VERSION_IN_USE == OFP_100
portVector[i].curr =0;
portVector[i].advertised =0;
portVector[i].supported =0;
portVector[i].peer =0;
portVector[i].curr_speed =0;
portVector[i].max_speed =0;
#endif
}
break;
}
case INITSTAGE_APPLICATION_LAYER:
{
//load XML config if specified.
cXMLElement* xmlDoc = par("configXML").xmlValue();
if(xmlDoc)
{
if(strcmp(xmlDoc->getName(), "config") == 0)
{
string switchName = getParentModule()->getSubmodule("eth", 0)->getSubmodule("mac")->par("address").stringValue();
if(cXMLElement* switchConfigXML = xmlDoc->getFirstChildWithAttribute("switch", "id", switchName.c_str()))
{//there is a config for this switch.
cXMLElementList flowTableXML = switchConfigXML->getChildrenByTagName("flowTable");
for (size_t i=0; i<flowTableXML.size(); i++)
{//the config contains a flow tables so set them.
int index = i;
if(const char* value = flowTableXML[i]->getAttribute("index"))
{
index = atoi(value);
} else if(flowTableXML.size() == 1)
{
// do nothing
} else
{
throw cRuntimeError ("OF_SwitchAgent::initialize(): could not read flow table the index is not specified.");
}
_flowTables[index]->importFromXML(flowTableXML[i]);
}
}
}
}
break;
}
default:
break;
}
}
void OF_RelayUnit::processDataPlanePacket(cMessage *msg)
{
dataPlanePacket++;
if (EthernetIIFrame *frame = dynamic_cast<EthernetIIFrame *>(msg))
{
//msg from dataplane
processFrame(frame);
}
}
void OF_RelayUnit::processFrame(EthernetIIFrame *frame)
{
//get all relevant match fiels
oxm_basic_match match = extractMatch(frame);
unsigned long hash = 0;
//emit id of ping packet to indicate where it was processed
if (dynamic_cast<ICMPMessage *>(frame->getEncapsulatedPacket()->getEncapsulatedPacket())
!= NULL)
{
ICMPMessage *icmpMessage =
(ICMPMessage *) frame->getEncapsulatedPacket()->getEncapsulatedPacket();
PingPayload * pingMsg =
(PingPayload *) icmpMessage->getEncapsulatedPacket();
//generate and emit hash
std::stringstream hashString;
hashString << "SeqNo-" << pingMsg->getSeqNo() << "-Pid-"
<< pingMsg->getOriginatorId();
hash = std::hash<std::string>()(hashString.str().c_str());
}
if (hash != 0)
{
emit(cpPingPacketHash, hash);
}
OF_FlowTableEntry *lookup = _flowTables[0]->lookup(match);
if (lookup != nullptr)
{
//lookup successful
flowTableHit++;
EV << "Found entry in flow table." << '\n';
for (size_t i = 0; i < lookup->getInstructions().size(); i++) {
ofp_action_output action_output = lookup->getInstructions()[i];
uint32_t outport = action_output.port;
if (outport == OFPP_CONTROLLER) {
emit(forwardToConSign,frame);
} else {
//send it out the dataplane on the specific port
send(frame->dup(), "dataPlaneOut", outport);
}
}
}
else
{
// lookup failed
flowTableMiss++;
EV << "No Entry Found contacting controller" << '\n';
emit(tableMissSign,frame);
}
}
oxm_basic_match OF_RelayUnit::extractMatch(EthernetIIFrame* frame)
{
oxm_basic_match match = oxm_basic_match();
//extract match fields
match.OFB_IN_PORT = frame->getArrivalGate()->getIndex();
match.OFB_ETH_SRC = frame->getSrc();
match.OFB_ETH_DST = frame->getDest();
match.OFB_ETH_TYPE = frame->getEtherType();
if(CoRE4INET::EthernetIIFrameWithQTag* qFrame =
dynamic_cast<CoRE4INET::EthernetIIFrameWithQTag*>(frame))
{
//we have a q frame!
match.OFB_VLAN_VID = qFrame->getVID();
match.OFB_VLAN_PCP = qFrame->getPcp();
} else {
match.OFB_VLAN_VID = 0;
match.OFB_VLAN_PCP = 0;
}
//extract ARP specific match fields if present
if (frame->getEtherType() == ETHERTYPE_ARP)
{
ARPPacket* arpPacket = check_and_cast<ARPPacket*>(
frame->getEncapsulatedPacket());
match.OFB_IP_PROTO = arpPacket->getOpcode();
match.OFB_IPV4_SRC = arpPacket->getSrcIPAddress();
match.OFB_IPV4_DST = arpPacket->getDestIPAddress();
}
//extract IPv4 fields if present
//if(frame->getEtherType()==IPv4Datagram) {
if (IPv4Datagram* ipv4Datagram =
dynamic_cast<IPv4Datagram*>(frame->getEncapsulatedPacket()))
{
match.OFB_IP_PROTO = ipv4Datagram->getTransportProtocol();
match.OFB_IPV4_SRC = ipv4Datagram->getSourceAddress().toIPv4();
match.OFB_IPV4_DST = ipv4Datagram->getDestinationAddress().toIPv4();
//extract transport if present
if (ITransportPacket* transport =
dynamic_cast<ITransportPacket*>(ipv4Datagram->getEncapsulatedPacket()))
{
// Transport packet.
match.OFB_TP_SRC = transport->getSourcePort();
match.OFB_TP_DST = transport->getDestinationPort();
}
}
return match;
}
// packet encapsulated and not stored in buffer
void OF_RelayUnit::executePacketOutAction(ofp_action_output *action_output, EthernetIIFrame *frame, uint32_t inport)
{
Enter_Method("executePacketOutAction");
uint32_t outport = action_output->port;
take(frame);
if (outport == OFPP_ANY)
{
EV << "Dropping packet" << '\n';
}
else if (outport == OFPP_FLOOD)
{
EV << "Flood Packet\n" << '\n';
unsigned int n = gateSize("dataPlaneOut");
for (unsigned int i=0; i<n; ++i)
{
if (i != inport && !(portVector[i].state & OFPPS_BLOCKED))
{
send(frame->dup(), "dataPlaneOut", i);
}
}
}
else
{
EV << "Send Packet\n" << '\n';
send(frame->dup(), "dataPlaneOut", outport);
}
drop(frame);
}
void OF_RelayUnit::handleMessage(cMessage *msg)
{
if (msg->arrivedOn("dataPlaneIn"))
{
processDataPlanePacket(msg);
}
delete msg;
}
// invoked by Spanning Tree module disable ports for broadcast packets
void OF_RelayUnit::disablePorts(vector<int> ports)
{
EV << "disablePorts method at " << this->getParentModule()->getFullPath() << '\n';
for (unsigned int i = 0; i<ports.size(); ++i)
{
portVector[ports[i]].state |= OFPPS_BLOCKED;
}
for(unsigned int i=0;i<portVector.size();++i)
{
EV << "Port: " << i << " Value: " << portVector[i].state << '\n';
}
if(par("highlightActivePorts").boolValue())
{
// Highlight links that belong to spanning tree
for (unsigned int i = 0; i < portVector.size(); ++i)
{
if (!(portVector[i].state & OFPPS_BLOCKED))
{
cGate *gateOut = getParentModule()->gate("gateDataPlane$o", i);
do {
cDisplayString& connDispStrOut = gateOut->getDisplayString();
connDispStrOut.parse("ls=green,3,dashed");
gateOut=gateOut->getNextGate();
} while (!gateOut->getOwnerModule()->getModuleType()->isSimple());
cGate *gateIn = getParentModule()->gate("gateDataPlane$i", i);
do {
cDisplayString& connDispStrIn = gateIn->getDisplayString();
connDispStrIn.parse("ls=green,3,dashed");
gateIn=gateIn->getPreviousGate();
} while (!gateIn->getOwnerModule()->getModuleType()->isSimple());
}
}
}
}
void OF_RelayUnit::finish()
{
// record statistics
recordScalar("packetsDataPlane", dataPlanePacket);
recordScalar("flowTableHit", flowTableHit);
recordScalar("flowTableMiss", flowTableMiss);
//print flow table
//xml head
std::ostringstream oss;
oss << "<config>" << endl;
oss << "<switch id=\"" << getParentModule()->getSubmodule("eth", 0)->getSubmodule("mac")->par("address").stringValue() << "\">" << endl;
for (size_t i = 0; i < _flowTables.size() ; i++)
{
oss << _flowTables[i]->exportToXML();
}
oss << "</switch>" << endl;
oss << "</config>" << endl;
cout << oss.str();
}
}
| 11,874
|
C++
|
.cc
| 319
| 28.630094
| 140
| 0.596307
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,194
|
OF_SwitchAgent.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/switch/base/engine/OF_SwitchAgent.cc
|
//STD
#include <sstream>
#include <string>
//inet
#include "inet/linklayer/ethernet/EtherMACBase.h"
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/networklayer/common/L3AddressResolver.h"
#include "inet/transportlayer/contract/ITransportPacket.h"
#include "inet/common/ModuleAccess.h"
#include "inet/networklayer/common/InterfaceTable.h"
#include "inet/networklayer/ipv4/ICMPMessage.h"
//Auto-generated Messages
#include "inet/networklayer/arp/ipv4/ARPPacket_m.h"
#include "inet/applications/pingapp/PingPayload_m.h"
//openflow
#include <openflow/openflow/protocol/OpenFlow.h>
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/messages/Open_Flow_Message_m.h"
#include "openflow/messages/OFP_Features_Reply_m.h"
#include "openflow/messages/OFP_Hello_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/messages/OFP_Packet_Out_m.h"
#include "openflow/messages/OFP_Flow_Mod_m.h"
//SDN4CoRE
#include <sdn4core/switch/base/engine/OF_RelayUnit.h>
#include <sdn4core/switch/base/engine/OF_SwitchAgent.h>
using namespace std;
using namespace inet;
using namespace openflow;
namespace SDN4CoRE{
Define_Module(OF_SwitchAgent);
#define MSGKIND_CONNECT 1
#define MSGKIND_SERVICETIME 3
OF_SwitchAgent::OF_SwitchAgent(){}
OF_SwitchAgent::~OF_SwitchAgent(){
for(auto&& entry : msgList) {
delete entry;
}
msgList.clear();
}
void OF_SwitchAgent::initialize(int stage){
switch(stage){
case INITSTAGE_LOCAL: {
relayUnit = dynamic_cast<OF_RelayUnit*> (getParentModule()->getSubmodule("relayUnit"));
ofBusy = false;
handleParameterChange(nullptr);
//stats
bufferSize = registerSignal("bufferSize");
waitingTime = registerSignal("waitingTime");
queueSize = registerSignal("queueSize");
//register relay unit signals
forwardToConSign = registerSignal("forwardToConSign");
tableMissSign = registerSignal("tableMissSign");
relayUnit->subscribe(forwardToConSign, this);
relayUnit->subscribe(tableMissSign, this);
controlPlanePacket=0l;
//init helper classes
buffer = Buffer((int)par("bufferCapacity"));
int numFlowTables = getParentModule()->getSubmodule("flowTables",0)->getVectorSize();
for (int i = 0; i < numFlowTables; i++) {
if(OF_FlowTable* table = dynamic_cast<OF_FlowTable*> (getParentModule()->getSubmodule("flowTables",i))){
_flowTables.push_back(table);
}
}
break;
}
case INITSTAGE_TRANSPORT_LAYER: {
//init socket to controller
const char *localAddress = par("localAddress");
int localPort = par("localPort");
socket.bind(*localAddress ? L3Address(localAddress) : L3Address(), localPort);
socket.setOutputGate(gate("controlPlaneOut"));
socket.setDataTransferMode(TCP_TRANSFER_OBJECT);
break;
}
case INITSTAGE_LAST: {
//schedule connection setup
cMessage *initiateConnection = new cMessage("initiateConnection");
initiateConnection->setKind(MSGKIND_CONNECT);
scheduleAt(par("connectAt").doubleValue(), initiateConnection);
break;
}
default:
break;
}
}
void OF_SwitchAgent::processControlPlanePacket(cMessage *msg){
controlPlanePacket++;
if (Open_Flow_Message *of_msg = dynamic_cast<Open_Flow_Message *>(msg)) { //msg from controller
switch ((ofp_type)of_msg->getHeader().type){
case OFPT_HELLO:
this->hasController = true;
break;
case OFPT_FEATURES_REQUEST:
handleFeaturesRequestMessage(of_msg);
break;
case OFPT_FLOW_MOD:
handleFlowModMessage(of_msg);
break;
case OFPT_PACKET_OUT:
handlePacketOutMessage(of_msg);
break;
default:
//TODO Process openflow Hello...?
break;
}
}
delete msg;
}
void OF_SwitchAgent::scheduleNextServiceTime(){
//check for more waiting packets
if (msgList.empty()) {
ofBusy = false;
} else {
cMessage* msgFromList = msgList.front();
msgList.pop_front();
scheduleForServiceTime(msgFromList);
emit(queueSize, static_cast<unsigned int>(msgList.size()));
emit(bufferSize, static_cast<int>(buffer.size()));
}
}
void OF_SwitchAgent::scheduleForServiceTime(cMessage *msg){
cMessage* event = new cMessage("event");
event->setKind(MSGKIND_SERVICETIME);
event->setContextPointer(msg);
scheduleAt(simTime() + ofServiceTime, event);
}
void OF_SwitchAgent::handleMessage(cMessage *msg){
if (msg->isSelfMessage()){
if (msg->getKind() == MSGKIND_CONNECT) {
EV << "starting of session" << '\n';
connect(""); // active OPEN
} else if (msg->getKind() == MSGKIND_SERVICETIME) {
//This is message which has been scheduled due to service time
//Get the Original message
cMessage* data_msg = (cMessage*) (msg->getContextPointer());
emit(waitingTime,
(simTime() - data_msg->getArrivalTime() - ofServiceTime));
//handle packet
processControlPlanePacket(data_msg);
//schedule next service time
scheduleNextServiceTime();
}
delete msg;
} else if (msg->getKind() == TCP_I_ESTABLISHED) { //fast handle for TCP Established
socket.processMessage(msg);
} else if(msg->arrivedOn("controlPlaneIn")){
simulateServiceTime(msg);
}
}
void OF_SwitchAgent::simulateServiceTime(cMessage* msg) {
//imlement service time
if(parallelProcessing || !ofBusy){
scheduleForServiceTime(msg);
ofBusy = true;
}else if (ofBusy) {
msgList.push_back(msg);
emit(queueSize, static_cast<unsigned int>(msgList.size()));
emit(bufferSize, static_cast<int>(buffer.size()));
}
}
void OF_SwitchAgent::connect(const char *addressToConnect){
socket.renewSocket();
const char *connectAddress;
int connectPort = par("connectPort").intValue();
if(strlen(addressToConnect) == 0){
connectAddress = par("connectAddress");
} else {
connectAddress = addressToConnect;
}
EV << "Sending Hello to " << connectAddress <<" \n";
socket.connect(L3AddressResolver().resolve(connectAddress), connectPort);
OFP_Hello *msg = OFMessageFactory::instance()->createHello();
socket.send(msg);
}
void OF_SwitchAgent::handleFeaturesRequestMessage(Open_Flow_Message *of_msg){
//prepare data
IInterfaceTable* inet_ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);
MACAddress mac = inet_ift->getInterface(0)->getMacAddress();
//output address
EV <<"SwitchID:" << mac.str() << " SwitchPath:" << this->getFullPath() << '\n';
if(relayUnit){
int dataPlaneGateSize = relayUnit->gateSize("dataPlaneOut");
//get message from factory
OFP_Features_Reply *featuresReply = OFMessageFactory::instance()->createFeaturesReply(mac.str(), buffer.getCapacity(), 1, 0, dataPlaneGateSize);
//send message
socket.send(featuresReply);
}
}
void OF_SwitchAgent::handleFlowModMessage(Open_Flow_Message *of_msg){
EV << "OFA_switch::handleFlowModMessage" << '\n';
if(OFP_Flow_Mod *flowModMsg = dynamic_cast<OFP_Flow_Mod *> (of_msg)){
_flowTables[flowModMsg->getTable_id()]->handleFlowMod(flowModMsg);
}
}
/**
* This method belongs here because it only operates on switchAgent members so there
* is no need to move it to the data plane
*/
void OF_SwitchAgent::handleMissMatchedPacket(EthernetIIFrame *frame){
OFP_Packet_In *packetIn;
if (sendCompletePacket || buffer.isfull()) {
#if OFP_VERSION_IN_USE == OFP_100
packetIn = OFMessageFactory::instance()->createPacketIn(OFPR_NO_MATCH,
frame);
#elif OFP_VERSION_IN_USE == OFP_151
packetIn = OFMessageFactory::instance()->createPacketIn(
OFPR_TABLE_MISS, frame);
#endif
} else {
auto buffer_id = buffer.storeMessage(frame->dup());
#if OFP_VERSION_IN_USE == OFP_100
packetIn = OFMessageFactory::instance()->createPacketIn(OFPR_NO_MATCH,
frame, buffer_id, false);
#elif OFP_VERSION_IN_USE == OFP_151
packetIn = OFMessageFactory::instance()->createPacketIn(
OFPR_TABLE_MISS, frame, buffer_id, false);
#endif
}
socket.send(packetIn);
}
void OF_SwitchAgent::handlePacketOutMessage(Open_Flow_Message *of_msg)
{
OFP_Packet_Out *packet_out_msg = (OFP_Packet_Out *) of_msg;
uint32_t bufferId = packet_out_msg->getBuffer_id();
uint32_t inPort = packet_out_msg->getIn_port();
unsigned int actions_size = packet_out_msg->getActionsArraySize();
EthernetIIFrame *frame;
if (bufferId != OFP_NO_BUFFER)
{
frame = buffer.returnMessage(bufferId);
}
else
{
frame = dynamic_cast<EthernetIIFrame *>(packet_out_msg->decapsulate());
}
for (unsigned int i = 0; i < actions_size; ++i)
{
auto action = packet_out_msg->getActions(i);
relayUnit->executePacketOutAction(&(action), frame, inPort);
}
take(frame);
delete frame;
}
void OF_SwitchAgent::receiveSignal(cComponent *src, simsignal_t id, cObject *value, cObject *details){
if(isConnectedToController()){
Enter_Method_Silent();
EthernetIIFrame* tmp = check_and_cast<EthernetIIFrame*>(value);
if(forwardToConSign == id){
forwardFrameToController(tmp);
}else if(tableMissSign == id){
handleMissMatchedPacket(tmp);
}
}
}
bool OF_SwitchAgent::isConnectedToController(void){
return (socket.getState() == TCPSocket::CONNECTED) && (this->hasController);
}
void OF_SwitchAgent::finish(){
recordScalar("packetsControlPlane", controlPlanePacket);
}
void OF_SwitchAgent::handleParameterChange(const char* parname) {
//read ned file parameters
if (!parname || !strcmp(parname, "serviceTime")){
ofServiceTime = par("serviceTime").doubleValue();
}
if (!parname || !strcmp(parname, "sendCompletePacket")){
sendCompletePacket = par("sendCompletePacket").boolValue();
}
if (!parname || !strcmp(parname, "parallelProcessing")){
parallelProcessing = par("parallelProcessing").boolValue();
}
}
void OF_SwitchAgent::forwardFrameToController(EthernetIIFrame* frame){
//send it to the controller
#if OFP_VERSION_IN_USE == OFP_100
OFP_Packet_In *packetIn =
OFMessageFactory::instance()->createPacketIn(OFPR_ACTION, frame);
#elif OFP_VERSION_IN_USE == OFP_151
OFP_Packet_In *packetIn = OFMessageFactory::instance()->createPacketIn(OFPR_ACTION_SET, frame->dup());
#endif
socket.send(packetIn);
}
} /*end namespace SDN4CoRE*/
| 11,011
|
C++
|
.cc
| 284
| 32.411972
| 152
| 0.671415
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,195
|
IPTunnelingControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/tunnel/IPTunnelingControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "IPTunnelingControllerApp.h"
//STD
#include <algorithm>
//inet
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/networklayer/arp/ipv4/ARPPacket_m.h"
#include "inet/networklayer/contract/ipv4/IPv4ControlInfo.h"
#include "inet/common/LayeredProtocolBase.h"
//openflow
#include <openflow/openflow/protocol/OFMessageFactory.h>
using namespace inet;
using namespace std;
using namespace openflow;
namespace SDN4CoRE {
Define_Module(IPTunnelingControllerApp);
void IPTunnelingControllerApp::initialize() {
PacketProcessorBase::initialize();
hostTable = check_and_cast<HostTable*>(
this->getModuleByPath(par("hostTablePath")));
deviceTable = check_and_cast<DeviceTable*>(
this->getModuleByPath(par("deviceTablePath")));
topology = check_and_cast<TopologyManagement*>(
this->getModuleByPath(par("topologyManagementPath")));
localIps = cStringTokenizer(par("controllerIps"), ",").asVector();
if (!localIps.empty()) {
_whitelist.addPacketFilters("ipDst", localIps);
}
defaultTimeToLive = par("timeToLive");
defaultMCTimeToLive = par("multicastTimeToLive");
fragmentTimeoutTime = par("fragmentTimeout");
forceBroadcast = par("forceBroadcast");
receiveMulticast = par("receiveMulticast");
receiveBroadcast = par("receiveBroadcast");
sendBroadcast = par("sendBroadcast");
sendMulticast = par("sendMulticast");
mtu = par("mtu");
numMulticast = numLocalDeliver = numDropped = numUnroutable = numForwarded = 0;
WATCH(numMulticast);
WATCH(numLocalDeliver);
WATCH(numDropped);
WATCH(numUnroutable);
WATCH(numForwarded);
}
void IPTunnelingControllerApp::handleParameterChange(const char* parname) {
PacketProcessorBase::handleParameterChange(parname);
if (!parname || !strcmp(parname, "controllerSrcMac")) {
if (par("controllerSrcMac").stdstringValue() == "auto") {
// assign automatic address
this->controllerSrcMac = inet::MACAddress::generateAutoAddress();
// change module parameter from "auto" to concrete address
par("controllerSrcMac").setStringValue(this->controllerSrcMac.str());
} else {
this->controllerSrcMac.setAddress(par("controllerSrcMac").stringValue());
}
}
}
void IPTunnelingControllerApp::refreshDisplay() const {
char buf[80] = "";
if (numForwarded > 0)
sprintf(buf + strlen(buf), "fwd:%d ", numForwarded);
if (numLocalDeliver > 0)
sprintf(buf + strlen(buf), "up:%d ", numLocalDeliver);
if (numMulticast > 0)
sprintf(buf + strlen(buf), "mcast:%d ", numMulticast);
if (numDropped > 0)
sprintf(buf + strlen(buf), "DROP:%d ", numDropped);
if (numUnroutable > 0)
sprintf(buf + strlen(buf), "UNROUTABLE:%d ", numUnroutable);
getDisplayString().setTagArg("t", 0, buf);
}
void IPTunnelingControllerApp::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj, cObject* details) {
if (id == BootedSignalId) {
isUp = true;
}
PacketProcessorBase::receiveSignal(src, id, obj, details);
}
void IPTunnelingControllerApp::handleMessage(cMessage *msg) {
if (dynamic_cast<RegisterTransportProtocolCommand *>(msg)) {
RegisterTransportProtocolCommand *command = check_and_cast<
RegisterTransportProtocolCommand *>(msg);
mapping.addProtocolMapping(command->getProtocol(),
msg->getArrivalGate()->getIndex());
delete msg;
} else {
//we do not implement queueing and delay in this ip version, so handle it directly
endService(PK(msg));
}
}
void IPTunnelingControllerApp::processPacketIn(OFP_Packet_In* packet_in_msg) {
if (EthernetIIFrame* eth =
dynamic_cast<EthernetIIFrame *>(packet_in_msg->getEncapsulatedPacket())) {
hostTable->update(packet_in_msg, controller->findSwitchInfoFor(packet_in_msg));
if (IPv4Datagram* ip =
dynamic_cast<IPv4Datagram *>(eth->getEncapsulatedPacket())) {
endService(ip->dup());
} else if (auto arpPacket = dynamic_cast<ARPPacket *>(eth->getEncapsulatedPacket())) {
handleIncomingARPPacket(packet_in_msg);
} else {
throw cRuntimeError(eth->getEncapsulatedPacket(),
"Unexpected packet type");
}
}
}
bool IPTunnelingControllerApp::isLocalIp(const IPv4Address& addr) {
return find(localIps.begin(), localIps.end(), addr.str()) != localIps.end();
}
IPv4Address IPTunnelingControllerApp::findBestFittingSrcIp(const IPv4Address& dest) {
if(localIps.empty()) {
return IPv4Address::UNSPECIFIED_ADDRESS;
}
//TODO find best matching src address, e.g. by matching subnets?
return IPv4Address(localIps[0].c_str());
}
void IPTunnelingControllerApp::endService(cPacket *packet) {
if (!isUp) {
EV_ERROR << "IPv4 is down -- discarding message\n";
delete packet;
return;
}
if (packet->getArrivalGate()->isName("transportIn")) {
handlePacketFromHL(packet);
} else { // from network
EV_INFO << "Received " << packet << " from OpenFlow network.\n";
if (auto dgram = dynamic_cast<IPv4Datagram *>(packet)) {
handleIncomingDatagram(dgram);
}
}
}
void IPTunnelingControllerApp::handleIncomingDatagram(IPv4Datagram *datagram) {
Enter_Method("handleIncomingDatagram");
ASSERT(datagram);
emit(LayeredProtocolBase::packetReceivedFromLowerSignal, datagram);
// hop counter decrement
datagram->setTimeToLive(datagram->getTimeToLive() - 1);
// remove control info
delete datagram->removeControlInfo();
//route packet
const IPv4Address& destAddr = datagram->getDestAddress();
EV_DETAIL << "Received datagram `" << datagram->getName() << "' with dest="
<< destAddr << "\n";
if (destAddr.isMulticast() && !receiveMulticast) {
dropPacketFromLower(datagram, "Skip forwarding of multicast datagram (forwarding disabled)");
} else if (destAddr.isLimitedBroadcastAddress() && !receiveBroadcast) {
dropPacketFromLower(datagram, "Skip forwarding of broadcast datagram (forwarding disabled)");
} else if (isLocalIp(destAddr) || destAddr.isMulticast()
|| destAddr.isLimitedBroadcastAddress()) {
// accept packet and forward!
reassembleAndDeliver(datagram);
} else {
dropPacketFromLower(datagram, "Skip forwarding of datagram with non local ip address");
}
}
void IPTunnelingControllerApp::handleIncomingARPPacket(OFP_Packet_In* packet_in_msg) {
ARPPacket* arp = dynamic_cast<ARPPacket *>(packet_in_msg->getEncapsulatedPacket()->getEncapsulatedPacket());
ASSERT(arp);
if(arp->getOpcode() == ARP_REQUEST && isLocalIp(arp->getDestIPAddress())) {
EV << "Received an ARP request for local controller IP, sending reply";
ARPPacket* reply = new ARPPacket("ControllerArpReply");
reply->setDestIPAddress(arp->getSrcIPAddress());
reply->setSrcIPAddress(arp->getDestIPAddress());
reply->setDestMACAddress(arp->getSrcMACAddress());
reply->setSrcMACAddress(controllerSrcMac);
reply->setOpcode(ARP_REPLY);
HostTable::HostEntry* host = hostTable->getHostForMacAddress(arp->getSrcMACAddress());
SwitchPort switchPort = topology->findEdgePort(host);
EthernetIIFrame* frame = etherEncap(reply, host, 0x0806);
uint32_t outports [] = { (uint32_t) switchPort.port};
OFP_Packet_Out* packetOut = OFMessageFactory::instance()->createPacketOut(outports, 1, -1, OFP_NO_BUFFER, frame);
// send to openflow channel
EV << "Send packet to OpenFlow channel" << '\n';
numPacketOut++;
TCPSocket *socket = controller->findSocketForChassisId(switchPort.switchId);
if(!socket) {
throw cRuntimeError("Could not find socket for switch id %s", switchPort.switchId.c_str());
}
packetOut->setKind(TCP_C_SEND);
controller->sendPacketOut(packetOut, socket);
}
}
void IPTunnelingControllerApp::reassembleAndDeliver(IPv4Datagram *datagram) {
EV_INFO << "Delivering " << datagram << " in OpenFlow IP tunnel.\n";
if (datagram->getSrcAddress().isUnspecified()) {
EV_WARN << "Received datagram '" << datagram->getName()
<< "' without source address filled in\n";
}
// reassemble the packet (if fragmented)
if (datagram->getFragmentOffset() != 0 || datagram->getMoreFragments()) {
EV_DETAIL << "Datagram fragment: offset="
<< datagram->getFragmentOffset() << ", MORE="
<< (datagram->getMoreFragments() ? "true" : "false")
<< ".\n";
// erase timed out fragments in fragmentation buffer; check every 10 seconds max
if (simTime() >= lastCheckTime + 10) {
lastCheckTime = simTime();
fragbuf.purgeStaleFragments(simTime() - fragmentTimeoutTime);
}
datagram = fragbuf.addFragment(datagram, simTime());
if (!datagram) {
EV_DETAIL << "No complete datagram yet.\n";
return;
}
EV_DETAIL << "This fragment completes the datagram.\n";
}
// decapsulate and send on appropriate output gate
int protocol = datagram->getTransportProtocol();
int gateindex = mapping.findOutputGateForProtocol(protocol);
// check if the transportOut port are connected, otherwise discard the packet
if (gateindex >= 0) {
cGate *outGate = gate("transportOut", gateindex);
if (outGate->isPathOK()) {
cPacket *packet = decapsulate(datagram);
send(packet, outGate);
emit(LayeredProtocolBase::packetSentToUpperSignal, packet);
numLocalDeliver++;
return;
}
}
dropPacketFromLower(datagram, "Transport protocol ID=" + to_string(protocol) + " not connected for OpenFlow IP tunnel");
}
void IPTunnelingControllerApp::handlePacketFromHL(cPacket *packet) {
EV_INFO << "Received " << packet << " from upper layer.\n";
emit(LayeredProtocolBase::packetReceivedFromUpperSignal, packet);
if (deviceTable->getDeviceCount() == 0) {
dropPacketFromUpper(packet, "No devices connected");
return;
}
IPv4ControlInfo *controlInfo = check_and_cast<IPv4ControlInfo *>(
packet->removeControlInfo());
IPv4Datagram *datagram = encapsulate(packet, controlInfo);
// TODO determine the outport from controlInfo interfaceId
datagramLocalOut(datagram);
}
void IPTunnelingControllerApp::datagramLocalOut(IPv4Datagram* datagram) {
const IPv4Address& destAddr = datagram->getDestAddress();
EV_DETAIL << "Sending datagram " << datagram << " with destination = "
<< destAddr << "\n";
if (destAddr.isMulticast()) {
if (sendMulticast) {
routeMulticastPacket(datagram);
} else {
dropPacketFromUpper(datagram,
"Multicast from upper layer is turned off for OpenFlow IP tunnel");
}
} else if (destAddr.isLimitedBroadcastAddress()) { // || rt->isLocalBroadcastAddress(destAddr))
if (sendBroadcast) {
routeLocalBroadcastPacket(datagram);
} else {
dropPacketFromUpper(datagram,
"Broadcast from upper layer is turned off for OpenFlow IP tunnel");
}
} else {
routeUnicastPacket(datagram);
}
}
void IPTunnelingControllerApp::routeUnicastPacket(IPv4Datagram* datagram) {
IPv4Address destAddr = datagram->getDestAddress();
EV_INFO << "Routing " << datagram << " with destination = " << destAddr << ", ";
// lookup in host table
HostTable::HostEntry* host = hostTable->getHostForIpAddress(destAddr);
if(!host) {
dropPacketFromUpper(datagram, "Unroutable, no host entry could be found");
//TODO do something like ARP?
} else {
//fragment and send
EV_INFO << "output to host " << host << "\n";
numForwarded++;
fragmentAndSend(datagram, host);
}
}
void IPTunnelingControllerApp::routeMulticastPacket(IPv4Datagram* datagram) {
throw cRuntimeError("OpenFlow Multicast not yet supported");
// const InterfaceEntry *ie = nullptr;
// if (multicastIFOption) {
// ie = multicastIFOption;
// EV_DETAIL << "multicast packet routed by socket option via output interface " << ie->getName() << "\n";
// }
// if (!ie) {
// IPv4Route *route = rt->findBestMatchingRoute(datagram->getDestAddress());
// if (route)
// ie = route->getInterface();
// if (ie)
// EV_DETAIL << "multicast packet routed by routing table via output interface " << ie->getName() << "\n";
// }
// if (!ie) {
// ie = rt->getInterfaceByAddress(datagram->getSrcAddress());
// if (ie)
// EV_DETAIL << "multicast packet routed by source address via output interface " << ie->getName() << "\n";
// }
// if (!ie) {
// ie = ift->getFirstMulticastInterface();
// if (ie)
// EV_DETAIL << "multicast packet routed via the first multicast interface " << ie->getName() << "\n";
// }
// return ie;
}
void IPTunnelingControllerApp::routeLocalBroadcastPacket(
IPv4Datagram* datagram) {
throw cRuntimeError("OpenFlow Broadcast not yet supported");
// The destination address is 255.255.255.255 or local subnet broadcast address.
// We always use 255.255.255.255 as nextHopAddress, because it is recognized by ARP,
// and mapped to the broadcast MAC address.
// if (destIE != nullptr) {
// fragmentAndSend(datagram, destIE, IPv4Address::ALLONES_ADDRESS);
// }
// else
// if (forceBroadcast) {
// // forward to each interface including loopback
// for (int i = 0; i < ift->getNumInterfaces(); i++) {
// const InterfaceEntry *ie = ift->getInterface(i);
// fragmentAndSend(datagram->dup(), ie, IPv4Address::ALLONES_ADDRESS);
// }
// delete datagram;
// }
// else {
// numDropped++;
// emit(LayeredProtocolBase::packetFromUpperDroppedSignal, datagram);
// delete datagram;
// }
}
cPacket *IPTunnelingControllerApp::decapsulate(IPv4Datagram *datagram) {
// decapsulate transport packet
cPacket *packet = datagram->decapsulate();
// create and fill in control info
IPv4ControlInfo *controlInfo = new IPv4ControlInfo();
controlInfo->setProtocol(datagram->getTransportProtocol());
controlInfo->setSrcAddr(datagram->getSrcAddress());
controlInfo->setDestAddr(datagram->getDestAddress());
controlInfo->setTypeOfService(datagram->getTypeOfService());
controlInfo->setInterfaceId(-1);
controlInfo->setTimeToLive(datagram->getTimeToLive());
// original IPv4 datagram might be needed in upper layers to send back ICMP error message
controlInfo->setOrigDatagram(datagram);
// attach control info
packet->setControlInfo(controlInfo);
return packet;
}
void IPTunnelingControllerApp::fragmentAndSend(IPv4Datagram *datagram, HostTable::HostEntry* host) {
// hop counter check
if (datagram->getTimeToLive() <= 0) {
dropPacketFromUpper(datagram, "Datagram TTL reached zero");
return;
}
// fill in source address
if (datagram->getSrcAddress().isUnspecified()) {
IPv4Address src = findBestFittingSrcIp(datagram->getDestAddress());
if(src.isUnspecified()) {
dropPacketFromUpper(datagram, "No controller source IP found for datagram");
return;
} else {
datagram->setSrcAddress(src);
}
}
// send datagram straight out if it doesn't require fragmentation (note: mtu==0 means infinite mtu)
if (mtu == 0 || datagram->getByteLength() <= mtu) {
sendDatagramToHost(datagram, host);
return;
}
// if "don't fragment" bit is set, throw datagram away and send ICMP error message
if (datagram->getDontFragment()) {
dropPacketFromUpper(datagram, "Datagram larger than MTU and don't fragment bit set");
return;
}
// FIXME some IP options should not be copied into each fragment, check their COPY bit
int headerLength = datagram->getHeaderLength();
int payloadLength = datagram->getByteLength() - headerLength;
int fragmentLength = ((mtu - headerLength) / 8) * 8; // payload only (without header)
if (fragmentLength <= 0) {
throw cRuntimeError("Cannot fragment datagram: MTU=%d too small for header size (%d bytes)", mtu, headerLength); // exception and not ICMP because this is likely a simulation configuration error, not something one wants to simulate
}
int offsetBase = datagram->getFragmentOffset();
int noOfFragments = (payloadLength + fragmentLength - 1) / fragmentLength;
EV_DETAIL << "Breaking datagram into " << noOfFragments << " fragments\n";
string fragMsgName = datagram->getName();
fragMsgName += "-frag";
// create and send fragments
for (int offset = 0; offset < payloadLength; offset += fragmentLength) {
bool lastFragment = (offset + fragmentLength >= payloadLength);
// length equal to fragmentLength, except for last fragment;
int thisFragmentLength = lastFragment ? payloadLength - offset : fragmentLength;
// FIXME is it ok that full encapsulated packet travels in every datagram fragment?
// should better travel in the last fragment only. Cf. with reassembly code!
IPv4Datagram *fragment = datagram->dup();
fragment->setName(fragMsgName.c_str());
// "more fragments" bit is unchanged in the last fragment, otherwise true
if (!lastFragment)
fragment->setMoreFragments(true);
fragment->setByteLength(headerLength + thisFragmentLength);
fragment->setFragmentOffset(offsetBase + offset);
sendDatagramToHost(fragment, host);
}
delete datagram;
}
void IPTunnelingControllerApp::sendDatagramToHost(IPv4Datagram *datagram, HostTable::HostEntry* host) {
ASSERT(host);
if(datagram->getByteLength() > MAX_ETHERNET_DATA_BYTES) {
throw cRuntimeError("Datagram to large for Ethernet Frame");
}
SwitchPort switchPort = topology->findEdgePort(host);
if (switchPort.empty()) {
dropPacketFromUpper(datagram, "Host has no edge port");
return;
}
EthernetIIFrame* frame = etherEncap(datagram, host);
uint32_t outports [] = { (uint32_t) switchPort.port};
OFP_Packet_Out* packetOut = OFMessageFactory::instance()->createPacketOut(outports, 1, -1, OFP_NO_BUFFER, frame);
// send to openflow channel
EV << "Send packet to OpenFlow channel" << '\n';
numPacketOut++;
TCPSocket *socket = controller->findSocketForChassisId(switchPort.switchId);
if(!socket) {
throw cRuntimeError("Could not find socket for switch id %s", switchPort.switchId.c_str());
}
packetOut->setKind(TCP_C_SEND);
controller->sendPacketOut(packetOut, socket);
}
IPv4Datagram *IPTunnelingControllerApp::encapsulate(cPacket *transportPacket,
IPv4ControlInfo *controlInfo) {
IPv4Datagram *datagram = createIPv4Datagram(transportPacket->getName());
datagram->setByteLength(IP_HEADER_BYTES);
datagram->encapsulate(transportPacket);
// set source and destination address
IPv4Address dest = controlInfo->getDestAddr();
datagram->setDestAddress(dest);
IPv4Address src = controlInfo->getSrcAddr();
// when source address was given, use it; otherwise it'll get the address
// of the outgoing interface after routing
if (!src.isUnspecified() && isLocalIp(src)) {
datagram->setSrcAddress(src);
}
// set other fields
datagram->setTypeOfService(controlInfo->getTypeOfService());
datagram->setIdentification(curFragmentId++);
datagram->setMoreFragments(false);
datagram->setDontFragment(controlInfo->getDontFragment());
datagram->setFragmentOffset(0);
short ttl;
if (controlInfo->getTimeToLive() > 0)
ttl = controlInfo->getTimeToLive();
else if (datagram->getDestAddress().isLinkLocalMulticast())
ttl = 1;
else if (datagram->getDestAddress().isMulticast())
ttl = defaultMCTimeToLive;
else
ttl = defaultTimeToLive;
datagram->setTimeToLive(ttl);
datagram->setTransportProtocol(controlInfo->getProtocol());
// setting IPv4 options is currently not supported
return datagram;
}
IPv4Datagram *IPTunnelingControllerApp::createIPv4Datagram(const char *name) {
return new IPv4Datagram(name);
}
void IPTunnelingControllerApp::dropPacketFromUpper(cMessage* packet, string reason) {
if(!reason.empty()) {
EV_ERROR << reason << ", dropping packet\n";
}
numDropped++;
emit(LayeredProtocolBase::packetFromUpperDroppedSignal, packet);
delete packet;
}
void IPTunnelingControllerApp::dropPacketFromLower(cMessage* packet, string reason) {
if(!reason.empty()) {
EV_ERROR << reason << ", dropping packet\n";
}
numUnroutable++;
emit(LayeredProtocolBase::packetFromLowerDroppedSignal, packet);
delete packet;
}
EthernetIIFrame* IPTunnelingControllerApp::etherEncap(
cPacket* packet, HostTable::HostEntry* host, int etherType) {
// create ether header
EthernetIIFrame* frame = new EthernetIIFrame(packet->getName(), 4); // kind 4 = color
frame->setDest(host->macAddress);
frame->setSrc(this->controllerSrcMac);
frame->setEtherType(etherType);
//TODO maybe support 8021Q options?
// pack and pad
ASSERT(frame->getByteLength() > 0); // length comes from msg file
frame->encapsulate(packet);
if (frame->getByteLength() < MIN_ETHERNET_FRAME_BYTES) {
frame->setByteLength(MIN_ETHERNET_FRAME_BYTES); // "padding"
}
return frame;
}
} /*end namespace SDN4CoRE*/
| 22,662
|
C++
|
.cc
| 500
| 39.304
| 239
| 0.681709
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,196
|
SomeipSDControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/someipSD/SomeipSDControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, Jan Schmitt-Solbrig, for HAW Hamburg
//
#include "SomeipSDControllerApp.h"
//STD
#include <sstream>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/transportlayer/udp/UDPPacket.h"
#include <inet/networklayer/contract/ipv4/IPv4Address.h>
#include <inet/networklayer/common/IPProtocolId_m.h>
//openflow
#include "openflow/messages/OFP_Flow_Mod_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
//CoRE4INET
#include "core4inet/utilities/customWatch.h"
using namespace inet;
using namespace std;
using namespace openflow;
using namespace CoRE4INET;
using namespace SOA4CoRE;
namespace SDN4CoRE {
#define MAJOR_VERSION 0xFF // see [PRS_SOMEIPSD_00351],[PRS_SOMEIPSD_00356],[PRS_SOMEIPSD_00386],[PRS_SOMEIPSD_00391]
#define MINOR_VERSION 0xFFFFFFFF // see [PRS_SOMEIPSD_00351],[PRS_SOMEIPSD_00356],[PRS_SOMEIPSD_00386],[PRS_SOMEIPSD_00391]
#define TTL 0xFFFFFF // see [PRS_SOMEIPSD_00351],[PRS_SOMEIPSD_00356],[PRS_SOMEIPSD_00386],[PRS_SOMEIPSD_00391]
#define SOMEIPSD_PORT 30490
Define_Module(SomeipSDControllerApp);
void SomeipSDControllerApp::initialize() {
PacketProcessorBase::initialize();
hostTable = check_and_cast<HostTable*>(
this->getModuleByPath(par("hostTablePath")));
deviceTable = check_and_cast<DeviceTable*>(
this->getModuleByPath(par("deviceTablePath")));
topology = check_and_cast<TopologyManagement*>(
this->getModuleByPath(par("topologyManagementPath")));
forwardOfferMulticast = this->par("forwardOfferMulticast");
someipMcastAddress = IPv4Address(par("someipMcastAddress").stringValue());
// 1. Create ServiceEntry - a static entry to answer the first incoming find-message
// ServiceEntry* entry = new ServiceEntry("ServiceEntry");
// entry->setType(SOA4CoRE::SomeIpSDEntryType::OFFER);
// entry->setIndex1stOptions(0);
// entry->setIndex2ndOptions(0);
// entry->setNum1stOptions(0);
// entry->setNum2ndOptions(0);
// entry->setServiceID(1);
// entry->setInstanceID(1);
// entry->setMajorVersion(MAJOR_VERSION);
// entry->setTTL(TTL);
// entry->setMinorVersion(MINOR_VERSION);
//Option UDP
// IPv4EndpointOption *ipv4EndpointOption = new IPv4EndpointOption("IPv4EndpointOption of Publisher");
// ipv4EndpointOption->setIpv4Address(IPv4Address("192.168.178.1"));
// ipv4EndpointOption->setL4Protocol(IPProtocolId::IP_PROT_UDP);
// ipv4EndpointOption->setPort(3171);
//Option TCP
// IPv4EndpointOption *ipv4EndpointOption2 = new IPv4EndpointOption("IPv4EndpointOption of Publisher");
// ipv4EndpointOption2->setIpv4Address(IPv4Address("192.168.178.1"));
// ipv4EndpointOption2->setL4Protocol(IPProtocolId::IP_PROT_TCP);
// ipv4EndpointOption2->setPort(3171);
// ServiceInstance instance;
// instance.entry = entry;
// instance.optionList.push_back(ipv4EndpointOption);
// instance.optionList.push_back(ipv4EndpointOption2);
// // 3. insert into map
// InstanceMap instances; // calls map constructor
// instances[entry->getInstanceID()] = instance;
// serviceTable[entry->getServiceID()] = instances;
myLayeredInformation.eth_src.setAddress("C0:C0:C0:C0:C0:C0");
myLayeredInformation.ip_src = L3Address("10.0.0.2");
myLayeredInformation.transport_src = SOMEIPSD_PORT;
myLayeredInformation.in_port = -1;
myLayeredInformation.sw_info = nullptr;
//[PRS_SOMEIPSD_00158] dThe Session-ID (SOME/IP header) shall start with 1 and
//be 1 even after wrapping.c(RS_SOMEIPSD_00001)
// important for the finds the controller sends
controllerRequestID = 0x0001;
WATCH_MAPMAP(serviceTable);
WATCH_LISTMAP(requestTable);
WATCH_LISTMAPMAP(subscriptionTable);
}
void SomeipSDControllerApp::processPacketIn(OFP_Packet_In* packet_in_msg) {
Switch_Info* swInfo = controller->findSwitchInfoFor(packet_in_msg);
// layer 2
if (EthernetIIFrame* eth = dynamic_cast<EthernetIIFrame *>(packet_in_msg->getEncapsulatedPacket())) {
//layer 3
if (INetworkDatagram* ip = dynamic_cast<INetworkDatagram *>(eth->getEncapsulatedPacket())) {
// layer 4
if (UDPPacket* transport = dynamic_cast<UDPPacket*>
(eth->getEncapsulatedPacket()->getEncapsulatedPacket())) {
if (SomeIpSDHeader* someIpSDHeader = dynamic_cast<SomeIpSDHeader*>
(transport->getEncapsulatedPacket())) {
if(ip->getSourceAddress() != myLayeredInformation.ip_src) {
hostTable->update(packet_in_msg, swInfo);
}
//set layeredInformation and attach control info
LayeredInformation* layeredInformation = new LayeredInformation();
layeredInformation->eth_src = eth->getSrc();
layeredInformation->eth_dst = eth->getDest();
layeredInformation->ip_src = ip->getSourceAddress();
layeredInformation->ip_dst = ip->getDestinationAddress();
layeredInformation->transport_src = transport->getSourcePort();
layeredInformation->transport_dst = transport->getDestinationPort();
layeredInformation->in_port = eth->getArrivalGate()->getIndex();
layeredInformation->sw_info = swInfo;
someIpSDHeader->setControlInfo(layeredInformation);
processSomeIpSDHeader(someIpSDHeader);
}
}
}
}
}
void SomeipSDControllerApp::processSomeIpSDHeader(SomeIpSDHeader* someIpSDHeader) {
std::list<SomeIpSDEntry*> entries = someIpSDHeader->getEncapEntries();
for (auto it = entries.begin(); it != entries.end(); ++it) {
switch ((*it)->getType()) {
case SOA4CoRE::SomeIpSDEntryType::FIND:
EV << "FIND ARRIVED" << endl;
processFindEntry(*it, someIpSDHeader);
break;
case SOA4CoRE::SomeIpSDEntryType::OFFER:
EV << "OFFER ARRIVED" << endl;
processOfferEntry(*it, someIpSDHeader);
break;
case SOA4CoRE::SomeIpSDEntryType::SUBSCRIBEVENTGROUP:
EV << "SUBSCRIBEVENTGROUP ARRIVED" << endl;
processSubscribeEventGroupEntry(*it, someIpSDHeader);
break;
case SOA4CoRE::SomeIpSDEntryType::SUBSCRIBEVENTGROUPACK:
EV << "SUBSCRIBEVENTGROUPACK ARRIVED" << endl;
processSubscribeEventGroupAckEntry(*it, someIpSDHeader);
break;
default:
EV << "Unknown type" << std::endl;
}
}
}
void SomeipSDControllerApp::processFindEntry(SomeIpSDEntry* findInquiry, SomeIpSDHeader* someIpSDHeader) {
LayeredInformation* findInfo = dynamic_cast<LayeredInformation*>(someIpSDHeader->getControlInfo());
std::list<ServiceInstance> entries = lookUpServiceInMap(findInquiry->getServiceID(), findInquiry->getInstanceID());
if(findInfo->ip_src == myLayeredInformation.ip_src) {
// this is a find forwarded by the controller
if(!entries.empty()) {
// we have already answered this when the offer arrived
return;
}
// still unknown so forward
sendFind(someIpSDHeader->dup(), someIpSDHeader);
} else if(entries.empty()) {
SomeIpSDHeader* myFind = buildFind(someIpSDHeader, findInquiry);
sendFind(myFind, someIpSDHeader);
FindRequest saveFind;
saveFind.requestHeader = someIpSDHeader->dup();
saveFind.layeredInformation = findInfo->dup();
saveFind.entry = dynamic_cast<ServiceEntry*>(findInquiry->dup());
saveFind.entry->setIndex1stOptions(0);
std::list<SomeIpSDOption*> findOptions = getEntryOptions(findInquiry, someIpSDHeader);
for (auto optIt = findOptions.begin(); optIt != findOptions.end(); optIt++) {
saveFind.optionList.push_back((*optIt));
}
// insert into map
uint16_t requestedServiceId = findInquiry->getServiceID();
auto found = requestTable.find(requestedServiceId);
if (found != requestTable.end()) {
for (auto findIt = found->second.begin(); findIt !=found->second.end(); findIt++){
if (findIt->entry->getInstanceID() == saveFind.entry->getInstanceID()){
if (findIt->layeredInformation->eth_src == saveFind.layeredInformation->eth_src) {
findIt->clear();
found->second.erase(findIt--);
}
}
}
requestTable[requestedServiceId].push_back(saveFind);
} else {
std::list<FindRequest> newFind = {saveFind};
requestTable[requestedServiceId] = newFind;
}
} else {
SomeIpSDHeader* foundOffer = buildOffer(someIpSDHeader, findInquiry, entries);
sendOffer(foundOffer, someIpSDHeader, findInfo, entries.front().layeredInformation);
// TODO maybe use controller layered info if multiple entries
}
}
void SomeipSDControllerApp::processOfferEntry(SomeIpSDEntry* offerEntry,SomeIpSDHeader* someIpSDHeader) {
LayeredInformation* info = dynamic_cast<LayeredInformation*>(someIpSDHeader->getControlInfo());
//toDo &&broadcastMulticast true
if (info->ip_dst.isMulticast() && forwardOfferMulticast) {
// broadcast offer, function is implemented in sendFind
SomeIpSDHeader* dupHeader = someIpSDHeader->dup();
dupHeader->removeControlInfo();
sendFind(dupHeader, someIpSDHeader);
}
if(info->ip_src == myLayeredInformation.ip_src) {
// this is an offer forwarded by the controller
return;
}
// update ServiceTable with offer
ServiceInstance instance;
instance.entry = dynamic_cast<ServiceEntry*>(offerEntry->dup());
instance.entry->setIndex1stOptions(0);
instance.layeredInformation = info->dup();
instance.optionList = getEntryOptions(offerEntry, someIpSDHeader);
updateServiceTable(instance);
// look for requested offer in requestTable
auto foundX = requestTable.find(offerEntry->getServiceID());
if(foundX != requestTable.end()) {
// to build an offer we need a list of ServiceInstances although we only have one offer
std::list<ServiceInstance> entries;
entries.push_back(instance);
// Iteration of the InstanceMap
std::list<FindRequest>& findInstances = foundX->second;
for (auto it = findInstances.begin(); it != findInstances.end(); it++) {
if ((it->entry->getInstanceID() == 0xFFFF) || (it->entry->getInstanceID() == instance.entry->getInstanceID())) {
SomeIpSDHeader* foundRequest = buildOffer(it->requestHeader, it->entry, entries);
sendOffer(foundRequest, it->requestHeader, it->layeredInformation, instance.layeredInformation);
it->clear();
findInstances.erase(it--);
}
}
if (findInstances.empty()){
requestTable.erase(foundX);
}
}
}
void SomeipSDControllerApp::processSubscribeEventGroupEntry(SomeIpSDEntry* entry,SomeIpSDHeader* someIpSDHeader) {
LayeredInformation* layeredInformation = dynamic_cast<LayeredInformation*>(someIpSDHeader->getControlInfo());
// find service to subscribe to is in our service table
std::list<ServiceInstance> instances = lookUpServiceInMap(entry->getServiceID(), entry->getInstanceID());
// TODO send NACK or throw error
if(instances.size() <= 0) {
throw cRuntimeError("The requested service instance to subscribe to could not be found!");
} else if(instances.size() > 1) {
throw cRuntimeError("Multiple instances known for subscription, but it should be unambiguous");
}
ServiceInstance& instance = instances.front(); // for readability and comfort
// get dest ip of the service and compare to the dest id in layered information
L3Address& destination = instance.layeredInformation->ip_src;
if (destination != layeredInformation->ip_dst && destination != myLayeredInformation.ip_src) {
throw cRuntimeError("The subscription was sent to a different destination than known to the controller for the service instance!");
}
auto entryOptions = getEntryOptions(entry, someIpSDHeader);
if(entryOptions.size() != 1) {
throw cRuntimeError("Exactly one endpoint information must be present in subscribtion.");
}
IPv4EndpointOption* endpoint = dynamic_cast<IPv4EndpointOption*>(entryOptions.front());
// update local subscription table
bool subKnown = false;
if(subscriptionTable.find(entry->getServiceID()) != subscriptionTable.end()) {
if(subscriptionTable[entry->getServiceID()].find(entry->getInstanceID()) != subscriptionTable[entry->getServiceID()].end()) {
// we know a subscription for this service instance
for (auto it = subscriptionTable[entry->getServiceID()][entry->getInstanceID()].begin();
it != subscriptionTable[entry->getServiceID()][entry->getInstanceID()].end();
it++) {
if(it->isConsumer(*(layeredInformation), *(endpoint))) {
// already known!
it->waitingForAck = true;
subKnown = true;
break;
}
}
} else {
subscriptionTable[entry->getServiceID()][entry->getInstanceID()] = ServiceInstanceSubscriptionList();
}
} else {
subscriptionTable[entry->getServiceID()] = IntanceSubscriptionMap();
subscriptionTable[entry->getServiceID()][entry->getInstanceID()] = ServiceInstanceSubscriptionList();
}
if(!subKnown) {
Subscription subscription;
subscription.service = ServiceIdentifier(entry->getServiceID(),entry->getInstanceID());
subscription.providerInformation = *(instance.layeredInformation);
subscription.consumerInformation = *(layeredInformation);
subscription.consumerEndpoint = *(endpoint);
subscription.waitingForAck = true;
subscriptionTable[entry->getServiceID()][entry->getInstanceID()].push_back(subscription);
}
delete endpoint;
// build subscribe eventgroup
SomeIpSDHeader* header = buildSubscribeEventGroup(someIpSDHeader, entry);
// build packet out
EthernetIIFrame* eth2Frame = encapSDHeader(header, layeredInformation, instance.layeredInformation);
uint32_t outports [] = {(uint32_t)instance.layeredInformation->in_port};
OFP_Packet_Out *packetOut = OFMessageFactory::instance()->createPacketOut(
outports, 1, OFPP_CONTROLLER, OFP_NO_BUFFER, eth2Frame);
packetOut->setKind(TCP_C_SEND);
controller->sendPacketOut(packetOut, instance.layeredInformation->sw_info->getSocket());
delete eth2Frame;
}
void SomeipSDControllerApp::processSubscribeEventGroupAckEntry(SomeIpSDEntry* entry, SomeIpSDHeader* someIpSDHeader) {
LayeredInformation* layeredInformation = dynamic_cast<LayeredInformation*>(someIpSDHeader->getControlInfo());
uint16_t serviceId = entry->getServiceID();
uint16_t instanceId = entry->getInstanceID();
// find subscription in subscription table
if(subscriptionTable.find(serviceId) == subscriptionTable.end()
|| subscriptionTable[serviceId].find(instanceId) == subscriptionTable[serviceId].end()) {
throw cRuntimeError("No subscription for service instance to be acknowledged.");
}
ServiceInstanceSubscriptionList& subscriptions = subscriptionTable[serviceId][instanceId];
bool requested = false;
for (auto iter = subscriptions.begin(); iter != subscriptions.end(); iter++) {
if(iter->waitingForAck && iter->consumerInformation.ip_src == layeredInformation->ip_dst) {
// subscription requested and response is for this specific consumer
requested = true;
iter->waitingForAck = false;
if(!iter->active) {
// set provider information from subscribe ack in subscription
auto options = getEntryOptions(entry, someIpSDHeader);
if (options.size() != 1) {
throw cRuntimeError("Subscription acknowledgement must have exactly one endpoint option");
}
if(IPv4EndpointOption* endpoint = dynamic_cast<IPv4EndpointOption*>(options.front())) {
iter->providerEndpoint = *endpoint;
iter->providerInformation = *layeredInformation;
delete endpoint;
} else {
throw cRuntimeError("Provider option is no IPv4 endpoint");
}
installFlowForSubscription(*iter);
// forward subscription ack to subscriber
SomeIpSDHeader* header = buildSubscribeEventGroupAck(someIpSDHeader, entry);
EthernetIIFrame* eth2Frame = encapSDHeader(header, layeredInformation, &iter->consumerInformation);
uint32_t outports [] = {(uint32_t)iter->consumerInformation.in_port};
OFP_Packet_Out *packetOut = OFMessageFactory::instance()->createPacketOut(
outports, 1, OFPP_CONTROLLER, OFP_NO_BUFFER, eth2Frame);
packetOut->setKind(TCP_C_SEND);
controller->sendPacketOut(packetOut, iter->consumerInformation.sw_info->getSocket());
delete eth2Frame;
iter->active = true;
}
// consumer handled the sub ack!
break;
}
}
if(!requested) {
throw cRuntimeError("No subscription requested for service instance.");
}
}
SomeIpSDHeader* SomeipSDControllerApp::buildFind(SomeIpSDHeader* findSource, SomeIpSDEntry* findInquiry){
// findSource --> information about requester in the layered information
SomeIpSDHeader* header = new SomeIpSDHeader("SOME/IP SD - FIND");
header->setRequestID(controllerRequestID++);
SomeIpSDEntry* newFind = findInquiry->dup();
int optionQuantity = findInquiry->getNum1stOptions();
newFind->setIndex1stOptions(0);
newFind->setNum1stOptions(optionQuantity);
//[PRS_SOMEIPSD_00157] The Session-ID (SOME/IP header) shall be incremented for every SOME/IP-SD message sent.(RS_SOMEIPSD_00001)
if (controllerRequestID == 0) {
//[PRS_SOMEIPSD_00159] The Session-ID (SOME/IP header) shall not be set to 0. (RS_SOMEIPSD_00001
controllerRequestID = 1;
}
header->encapEntry(newFind);
std::list<SomeIpSDOption*> oldOptionList = getEntryOptions(findInquiry, findSource);
for (auto it = oldOptionList.begin(); it != oldOptionList.end(); it++) {
header->encapOption(*it);
}
return header;
}
SomeIpSDHeader* SomeipSDControllerApp::buildOffer(SomeIpSDHeader* findSource, SomeIpSDEntry* findEntry, list<ServiceInstance>& foundInstances){
// findSource --> information about requester in the layered information
// findEntry --> information what is requested
// list foundEntries --> struct with found entries and list of options
SomeIpSDHeader* header = new SomeIpSDHeader("SOME/IP SD - OFFER");
header->setRequestID(findSource->getRequestID());
// create offer - encap each found entry with corresponding options
int optionsIndex = 0;
for (auto it = foundInstances.begin(); it != foundInstances.end(); it++) {
SomeipSDControllerApp::ServiceInstance& instance = *it;
int numOptions = instance.optionList.size();
ServiceEntry* entry = instance.entry->dup();
entry->setNum1stOptions(numOptions);
entry->setIndex1stOptions(optionsIndex);
header->encapEntry(entry);
if (numOptions != 0) {
for (auto optIt = instance.optionList.begin(); optIt != instance.optionList.end(); optIt++) {
header->encapOption((*optIt)->dup());
}
}
optionsIndex += numOptions;
}
return header;
}
SOA4CoRE::SomeIpSDHeader* SomeipSDControllerApp::buildSubscribeEventGroup(
SOA4CoRE::SomeIpSDHeader* source, SOA4CoRE::SomeIpSDEntry* entry) {
SomeIpSDHeader* header = new SomeIpSDHeader("SOME/IP SD - SUBSCRIBEEVENTGROUP");
header->setRequestID(source->getRequestID());
auto entryOptions = getEntryOptions(entry, source);
auto entryDup = entry->dup();
entryDup->setNum1stOptions(entryOptions.size());
entryDup->setIndex1stOptions(0);
if (entryOptions.size() > 0) {
for (auto it = entryOptions.begin(); it != entryOptions.end(); it++) {
header->encapOption((*it));
}
}
header->encapEntry(entryDup);
return header;
}
SOA4CoRE::SomeIpSDHeader* SomeipSDControllerApp::buildSubscribeEventGroupAck(
SOA4CoRE::SomeIpSDHeader* source, SOA4CoRE::SomeIpSDEntry* entry) {
SomeIpSDHeader* header = new SomeIpSDHeader("SOME/IP SD - SUBSCRIBEEVENTGROUPACK");
header->setRequestID(source->getRequestID());
auto entryOptions = getEntryOptions(entry, source);
auto entryDup = entry->dup();
entryDup->setNum1stOptions(entryOptions.size());
entryDup->setIndex1stOptions(0);
if (entryOptions.size() > 0) {
for (auto it = entryOptions.begin(); it != entryOptions.end(); it++) {
header->encapOption((*it));
}
}
header->encapEntry(entryDup);
return header;
}
void SomeipSDControllerApp::sendFind(SomeIpSDHeader* find, SomeIpSDHeader* findSource){
LayeredInformation* info = dynamic_cast<LayeredInformation*>(findSource->getControlInfo());
//Layer 4
UDPPacket *udpPacket = new UDPPacket(find->getName());
udpPacket->setByteLength(UDP_HEADER_BYTES);
udpPacket->encapsulate(find);
udpPacket->setSourcePort(myLayeredInformation.transport_src);
udpPacket->setDestinationPort(SOMEIPSD_PORT);
//Layer 3
IPv4Datagram *datagram = new IPv4Datagram(find->getName());
IPv4Address src = myLayeredInformation.ip_src.toIPv4();
short ttl = 1;
datagram->setByteLength(IP_HEADER_BYTES);
datagram->encapsulate(udpPacket);
datagram->setSrcAddress(src);
datagram->setDestinationAddress(someipMcastAddress);
datagram->setMoreFragments(false);
datagram->setTimeToLive(ttl);
datagram->setTransportProtocol(17); //the UDP-standard protocol-id
// Layer 2
EthernetIIFrame *eth2Frame = new EthernetIIFrame(find->getName());
eth2Frame->setSrc(myLayeredInformation.eth_src);
eth2Frame->encapsulate(datagram);
if (eth2Frame->getByteLength() < MIN_ETHERNET_FRAME_BYTES)
eth2Frame->setByteLength(MIN_ETHERNET_FRAME_BYTES); // "padding"
// Openflow
OFP_Packet_Out *packetOut = new OFP_Packet_Out("packetOut");
ofp_header header = packetOut->getHeader();
header.version = OFP_VERSION;
header.type = OFPT_PACKET_OUT;
packetOut->setHeader(header);
packetOut->setBuffer_id(OFP_NO_BUFFER);
packetOut->setByteLength(24);
packetOut->encapsulate(eth2Frame);
ofp_action_output *action_output = new ofp_action_output();
action_output->port = OFPP_FLOOD;
packetOut->setIn_port(info->in_port);
packetOut->setActionsArraySize(1);
packetOut->setActions(0, *action_output);
packetOut->setKind(TCP_C_SEND);
controller->sendPacketOut(packetOut, info->sw_info->getSocket());
}
void SomeipSDControllerApp::sendOffer(SomeIpSDHeader* offer, SomeIpSDHeader* findSource, LayeredInformation* infoFind, LayeredInformation* infoOffer){
EthernetIIFrame *eth2Frame = encapSDHeader(offer, infoOffer, infoFind);
uint32_t outports [] = {(uint32_t)infoFind->in_port};
OFP_Packet_Out *packetOut = OFMessageFactory::instance()->createPacketOut(
outports, 1, OFPP_CONTROLLER, OFP_NO_BUFFER, eth2Frame);
packetOut->setKind(TCP_C_SEND);
controller->sendPacketOut(packetOut, infoFind->sw_info->getSocket());
delete eth2Frame;
}
void SomeipSDControllerApp::installFlowForSubscription(Subscription& sub) {
// flow specification
IPv4Address ip_src = sub.providerEndpoint.getIpv4Address();
uint16_t tp_src = sub.providerEndpoint.getPort();
uint8_t ip_proto = sub.consumerEndpoint.getL4Protocol();
IPv4Address ip_dst = sub.consumerEndpoint.getIpv4Address();
uint16_t tp_dst = sub.consumerEndpoint.getPort();
IPv4Address ip_host_dst = sub.getDstHostIp();
// TODO add mcast support!!
// bool isMcast = sub.isMcast();
// find route from the switch were the subAck arrived to the consumer IP
TopologyManagement::Route route = topology->findRoute(
topology->findEdgePort(ip_src).switchId, ip_host_dst);
if(route.empty()){
throw cRuntimeError("Could not find a route for acknowledged subscription");
}
// create the match
auto builder = OFMatchFactory::getBuilder();
builder->setField(OFPXMT_OFB_IPV4_SRC, &(ip_src));
builder->setField(OFPXMT_OFB_UDP_SRC, &(tp_src));
builder->setField(OFPXMT_OFB_IP_PROTO, &(ip_proto));
builder->setField(OFPXMT_OFB_IPV4_DST, &(ip_dst));
builder->setField(OFPXMT_OFB_UDP_DST, &(tp_dst));
for(SwitchPort& switchPort : route) {
int inport = topology->findOutportAtSwitch(switchPort.switchId, ip_src);
builder->setField(OFPXMT_OFB_IN_PORT, &(inport));
oxm_basic_match match = builder->build();
TCPSocket* socket = controller->findSocketForChassisId(switchPort.switchId);
sendFlowModMessage(ofp_flow_mod_command::OFPFC_ADD, match, switchPort.port, socket, _idleTimeout, _hardTimeout);
}
}
list<SomeIpSDOption*> SomeipSDControllerApp::getEntryOptions(SomeIpSDEntry* xEntry, SomeIpSDHeader* header) {
int optionPosition = xEntry->getIndex1stOptions();
int optionQuantity = xEntry->getNum1stOptions();
std::list<SomeIpSDOption*> optionList;
std::list<SomeIpSDOption*> optList = header->getEncapOptions();
std::_List_iterator<SomeIpSDOption*> optionListIterator = optList.begin();
std::advance(optionListIterator, optionPosition);
for (int firstOptionsIdx = 0; firstOptionsIdx < optionQuantity; firstOptionsIdx++) {
SomeIpSDOption* option = *optionListIterator;
optionList.push_back(option->dup());
std::advance(optionListIterator, 1);
}
return optionList;
}
void SomeipSDControllerApp::updateServiceTable(ServiceInstance& newInfo) {
uint16_t serviceId = newInfo.entry->getServiceID();
uint16_t instanceId = newInfo.entry->getInstanceID(); //Which Instance is offered
//ServiceID exists in ServiceTable?
auto found = serviceTable.find(serviceId);
if (found != serviceTable.end()) {
//InstanceID exists in Table?
auto foundInstance = found->second.find(instanceId);
if (foundInstance != found->second.end()) {
// Case 1: ServiceID and InstanceID exist -> update value of InstanceMap -> entry
ServiceInstance& serviceInstance = foundInstance->second;//
for (auto oldOptionIter = serviceInstance.optionList.begin(); oldOptionIter != serviceInstance.optionList.end(); ++oldOptionIter) {
bool update = false;
//check if there is already an option of the same type
for (auto newOptionIter = newInfo.optionList.begin(); newOptionIter != newInfo.optionList.end(); newOptionIter++) {
if((*newOptionIter)->getType() == (*oldOptionIter)->getType()) {
// option of same type exists
// there can be multiple ipv4 options for different protocols
if(IPv4EndpointOption* newOption = dynamic_cast<SOA4CoRE::IPv4EndpointOption*>(*newOptionIter)) {
if(IPv4EndpointOption* oldOption = dynamic_cast<SOA4CoRE::IPv4EndpointOption*>(*oldOptionIter)) {
if (newOption->getL4Protocol() == oldOption->getL4Protocol()) {
// mark for replacement
update = true;
}
}
} else {
// both should not be IPv4 so mark for replacement
update = true;
}
}
if(update) {
//already found
break;
}
}
if(!update) {
// insert old option
newInfo.optionList.push_back((*oldOptionIter)->dup());
}
}
// now newInfo is complete
// cleanup old instance
serviceInstance.clear();
} else {
// Case 2: ServiceID exists but instance unknown -> update InstanceMap new key value
}
} else {
// Case 3: neither service nor instance known -> update serviceTable key key value
serviceTable[serviceId] = InstanceMap();
}
serviceTable[serviceId][instanceId] = newInfo;
}
list<SomeipSDControllerApp::ServiceInstance> SomeipSDControllerApp::lookUpServiceInMap(uint16_t requestedServiceId, uint16_t requestedInstanceId){
list<ServiceInstance> returnList;
auto found = serviceTable.find(requestedServiceId);
if (found != serviceTable.end()) {
if (requestedInstanceId == 0xFFFF){
//all InstanceIDs shall be returned [PRS_SOMEIPSD_00351]
for (auto iter = found->second.begin(); iter != found->second.end(); iter++) {
returnList.push_back(iter->second);
}
} else {
auto foundInstance = found->second.find(requestedInstanceId);
if (foundInstance != found->second.end()) {
returnList.push_back(foundInstance->second);
}
}
}
return returnList;
}
inet::EthernetIIFrame* SomeipSDControllerApp::encapSDHeader(
SomeIpSDHeader* header, inet::MACAddress eth_src,
inet::MACAddress eth_dst, inet::L3Address ip_src,
inet::L3Address ip_dst, int udp_src, int udp_dst) {
//Layer 4
UDPPacket *udpPacket = new UDPPacket(header->getName());
udpPacket->setByteLength(UDP_HEADER_BYTES);
udpPacket->setSourcePort(udp_src);
udpPacket->setDestinationPort(udp_dst);
udpPacket->encapsulate(header);
//Layer 3
IPv4Datagram *datagram = new IPv4Datagram(header->getName());
datagram->setByteLength(IP_HEADER_BYTES);
datagram->setDestAddress(ip_dst.toIPv4());
datagram->setSrcAddress(ip_src.toIPv4());
datagram->setMoreFragments(false);
datagram->setTimeToLive(1);
datagram->setTransportProtocol(IP_PROT_UDP); //the UDP-standard protocol-id
datagram->encapsulate(udpPacket);
// Layer 2
EthernetIIFrame *eth2Frame = new EthernetIIFrame(header->getName());
eth2Frame->setSrc(eth_src);
eth2Frame->setDest(eth_dst);
eth2Frame->encapsulate(datagram);
if (eth2Frame->getByteLength() < MIN_ETHERNET_FRAME_BYTES)
eth2Frame->setByteLength(MIN_ETHERNET_FRAME_BYTES); // "padding"
return eth2Frame;
}
inet::EthernetIIFrame* SomeipSDControllerApp::encapSDHeader(
SomeIpSDHeader* header, LayeredInformation* bedirectionInfo) {
return encapSDHeader(header,
bedirectionInfo->eth_src, bedirectionInfo->eth_dst,
bedirectionInfo->ip_src, bedirectionInfo->ip_dst,
bedirectionInfo->transport_src, bedirectionInfo->transport_dst);
}
inet::EthernetIIFrame* SomeipSDControllerApp::encapSDHeader(
SomeIpSDHeader* header, LayeredInformation* src, LayeredInformation* dst) {
return encapSDHeader(header,
src->eth_src, dst->eth_src,
src->ip_src, dst->ip_src,
src->transport_src, dst->transport_src);
}
} /*end namespace SDN4CoRE*/
| 33,552
|
C++
|
.cc
| 637
| 43.040816
| 151
| 0.661413
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,197
|
StreamReservationControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/srp/StreamReservationControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, Tobias Haugg, for HAW Hamburg
//
#include "sdn4core/controllerApps/srp/StreamReservationControllerApp.h"
#include "sdn4core/utility/dynamicmodules/DynamicModuleHandling.h"
//STD
#include <sstream>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//AUTO_GENERATED MESSAGES
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/contract/ExtendedIeee802Ctrl_m.h"
//openflow
#include "openflow/messages/OFP_Flow_Mod_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/controller/OF_Controller.h"
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
using namespace inet;
using namespace CoRE4INET;
using namespace std;
using namespace openflow;
namespace SDN4CoRE{
Define_Module(StreamReservationControllerApp);
const char StreamReservationControllerApp::SRPTABLEMANAGERMODULEPATH[] = "sdn4core.controllerState.srp.SRPTableManagement";
void StreamReservationControllerApp::initialize() {
PacketProcessorBase::initialize();
// try to locate the macTableManager
_srpManager = tryLocateStateManager<SRPTableManagement*>("srpTableManagement");
if(!_srpManager) {
// create the mac manager
_srpManager = dynamic_cast<SRPTableManagement*>(
createFinalizeAndScheduleDynamicModule(SRPTABLEMANAGERMODULEPATH,
"srpTableManagement", this->getParentModule()->getSubmodule("controllerState"), false));
if(!_srpManager){
throw cRuntimeError("Could not create SRPTableManagement.");
}
}
}
void StreamReservationControllerApp::receiveSignal(cComponent* src, simsignal_t id, cObject* obj, cObject* details) {
if (id == PacketExperimenterSignalId) { // this msg could be from SRProtocol
if(OFP_Packet_In* packetIn = dynamic_cast<OFP_Packet_In*>(obj)){
if(CoRE4INET::SRPFrame* srpFrame = dynamic_cast<CoRE4INET::SRPFrame*>(packetIn->getEncapsulatedPacket())){
if(CoRE4INET::ListenerReady* listenerReady = dynamic_cast<CoRE4INET::ListenerReady*>(srpFrame)){
forwardListenerReady(packetIn);
}else {
throw cRuntimeError("Handling for SRP frames other than listener ready not yet implemented.");
}
}
}
}else {
PacketProcessorBase::receiveSignal(src, id, obj, details);
}
}
void StreamReservationControllerApp::forwardListenerReady(OFP_Packet_In* packetIn){
Switch_Info* swInfo = controller->findSwitchInfoFor(packetIn);
CoRE4INET::ListenerReady* listenerReady = dynamic_cast<CoRE4INET::ListenerReady*>(packetIn->getEncapsulatedPacket());
uint32 talkerPort = (uint32) _srpManager->getTalkerPort(swInfo, listenerReady->getStreamID(), listenerReady->getVlan_identifier());
// encapsulate srp
inet::EthernetIIFrame * frame = new inet::EthernetIIFrame(listenerReady->getName());
frame->setDest(SRP_ADDRESS);
frame->setEtherType(MSRP_ETHERTYPE);
frame->encapsulate(listenerReady->dup());
// create packet out
TCPSocket *socket = controller->findSocketFor(packetIn);
uint32 outports [] = { talkerPort};
OFP_Packet_Out *packetOut = OFMessageFactory::instance()->createPacketOut(outports, 1, -1, packetIn->getBuffer_id(), frame);
// send packet out
socket->send(packetOut);
delete frame;
}
void StreamReservationControllerApp::forwardTalkerAdvertise(OFP_Packet_In* packetIn){
Switch_Info * swInfo = controller->findSwitchInfoFor(packetIn);
inet::EthernetIIFrame * frame = dynamic_cast<inet::EthernetIIFrame *>( packetIn->getEncapsulatedPacket()->dup());
CoRE4INET::TalkerAdvertise* talkerAdvertise = dynamic_cast<CoRE4INET::TalkerAdvertise *>(frame->getEncapsulatedPacket());
int talkerPort = _srpManager->getTalkerPort(swInfo, talkerAdvertise->getStreamID(), talkerAdvertise->getVlan_identifier());
TCPSocket *socket = controller->findSocketFor(packetIn);
// create packet out
uint32 outports [] = { OFPP_FLOOD };
OFP_Packet_Out *packetOut = OFMessageFactory::instance()->createPacketOut(outports, 1, talkerPort, packetIn->getBuffer_id(), frame);
// send packet out
socket->send(packetOut);
delete frame;
}
void StreamReservationControllerApp::processPacketIn(OFP_Packet_In* packetIn) {
if (EthernetIIFrame * ethFrame = dynamic_cast<EthernetIIFrame *>(packetIn->getEncapsulatedPacket())) {
if (dynamic_cast<SRPFrame *>(ethFrame->getEncapsulatedPacket())) {
handleSRPFromDataplane(packetIn);
}
}
}
void StreamReservationControllerApp::handleSRPFromDataplane(OFP_Packet_In* packetIn) {
Switch_Info * swInfo = controller->findSwitchInfoFor(packetIn);
int arrivalPort = packetIn->getEncapsulatedPacket()->getArrivalGate()->getIndex();
//get SRP Frame
if( CoRE4INET::SRPFrame *srpFrame = dynamic_cast<CoRE4INET::SRPFrame *>(packetIn->getEncapsulatedPacket()->getEncapsulatedPacket())){
if (CoRE4INET::TalkerAdvertise* talkerAdvertise = dynamic_cast<CoRE4INET::TalkerAdvertise*>(srpFrame)){
_srpManager->registerTalker(swInfo, arrivalPort, talkerAdvertise);
updateSwitchSRPTable(packetIn);
forwardTalkerAdvertise(packetIn);
} else if (CoRE4INET::ListenerReady* listenerReady = dynamic_cast<CoRE4INET::ListenerReady*>(srpFrame)) {
bool updated = _srpManager->registerListener(swInfo, arrivalPort, listenerReady);
if (updated) {
// update forwarding rule
SRPTableManagement::SRPForwardingInfo_t* fwd = _srpManager->getForwardingInfoForStreamID (swInfo, listenerReady->getStreamID(), listenerReady->getVlan_identifier());
auto builder = OFMatchFactory::getBuilder();
builder->setField(OFPXMT_OFB_IN_PORT, &fwd->inPort);
builder->setField(OFPXMT_OFB_ETH_DST, &fwd->dest);
uint16_t avb_type = 0x8100;
builder->setField(OFPXMT_OFB_ETH_TYPE, &avb_type);
builder->setField(OFPXMT_OFB_VLAN_VID, &fwd->vlanID);
builder->setField(OFPXMT_OFB_VLAN_PCP, &fwd->pcp);
oxm_basic_match match = builder->build();
// send flow mod and update SRTable
TCPSocket * socket = controller->findSocketFor(packetIn);
sendSRPFlowModMessage(OFPFC_ADD, match, fwd->outports, socket, this->getIdleTimeout(), this->getHardTimeout());
updateSwitchSRPTable(packetIn);
delete fwd;
}
} else {
throw cRuntimeError("Handling for SRP frames other than listener ready and talker advertise not yet implemented.");
}
}
}
void StreamReservationControllerApp::sendSRPFlowModMessage(ofp_flow_mod_command mod_com, const oxm_basic_match &match, std::vector<int> outports, TCPSocket * socket, int idleTimeOut =0 , int hardTimeOut=0){
EV << "sendFlowModMessage" << '\n';
numFlowMod++;
int numOutPorts = outports.size();
uint32_t out[numOutPorts];
for(int i=0; i<numOutPorts; i++) {
out[i] = outports[i];
}
OFP_Flow_Mod* flow_mod_msg = OFMessageFactory::instance()->createFlowModMessage(mod_com, match, 5000, out, numOutPorts, idleTimeOut, hardTimeOut);
socket->send(flow_mod_msg);
}
void StreamReservationControllerApp::updateSwitchSRPTable(OFP_Packet_In* packetIn) {
TCPSocket *socket = controller->findSocketFor(packetIn);
OFP_Packet_Out *packetOut = new OFP_Packet_Out("forwardSRP");
ofp_header header = packetOut->getHeader();
header.version = OFP_VERSION;
header.type = OFPT_VENDOR;
packetOut->setHeader(header);
packetOut->setBuffer_id(packetIn->getBuffer_id());
packetOut->setByteLength(24);
omnetpp::cPacket* packet = packetIn->getEncapsulatedPacket()->getEncapsulatedPacket();
CoRE4INET::SRPFrame* toSwtich = dynamic_cast<CoRE4INET::SRPFrame *>(packet->dup());
packetOut->encapsulate(toSwtich);
packetOut->setIn_port(packetIn->getEncapsulatedPacket()->getArrivalGate()->getIndex());
socket->send(packetOut);
}
bool StreamReservationControllerApp::loadOfflineConfigFromXML(Switch_Info* info) {
// Enter_Method("loadOfflineConfigFromXML()");
//load XML config if specified.
bool changed = false;
cXMLElement* xmlDoc = par("configXML").xmlValue();
if(xmlDoc)
{//we got an XML document for config set.
changed |= _srpManager->loadConfigForSwitch(info->getMacAddress(), xmlDoc);
}
return changed;
}
void StreamReservationControllerApp::processSwitchConnection(openflow::Switch_Info* info) {
// Enter_Method("processSwitchConnection()");
loadOfflineConfigFromXML(info);
installSRPRule(info);
}
void StreamReservationControllerApp::installSRPRule(openflow::Switch_Info* info){
auto builder = OFMatchFactory::getBuilder();
uint16_t avb_type = 0x22EA;
builder->setField(OFPXMT_OFB_ETH_TYPE, &avb_type);
oxm_basic_match match = builder->build();
sendFlowModMessage(OFPFC_ADD, match,OFPP_CONTROLLER,info->getSocket(),0,0);
}
std::string StreamReservationControllerApp::stateToXML() {
ostringstream oss;
string tab = "\t";
oss << "<controller>" << endl;
_srpManager->dumpConfigToStream(oss, 2);
oss << "</controller>" << endl;
return oss.str();
}
} /*end namespace SDN4CoRE*/
| 10,173
|
C++
|
.cc
| 198
| 45.459596
| 206
| 0.721173
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,198
|
TSNLearningControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/tsn/TSNLearningControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "TSNLearningControllerApp.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
using namespace openflow;
namespace SDN4CoRE{
Define_Module(TSNLearningControllerApp);
void TSNLearningControllerApp::handleParameterChange(const char* parname)
{
AVBLearningControllerApp::handleParameterChange(parname);
if (!parname || !strcmp(parname, "staticPriorities"))
{
_staticPriorities = cStringTokenizer(par("staticPriorities"), ",").asIntVector();
}
}
oxm_basic_match TSNLearningControllerApp::createMatchFromPacketIn(
OFP_Packet_In* packetIn)
{
if(CoRE4INET::EthernetIIFrameWithQTag* qframe = dynamic_cast<CoRE4INET::EthernetIIFrameWithQTag *>(packetIn->getEncapsulatedPacket()))
{
CommonHeaderFields headerFields = extractCommonHeaderFields(packetIn);
uint8_t vlanpcp = qframe->getPcp();
auto builder = OFMatchFactory::getBuilder();
builder->setField(OFPXMT_OFB_ETH_DST, &headerFields.dst_mac);
builder->setField(OFPXMT_OFB_ETH_TYPE, &headerFields.eth_type);
builder->setField(OFPXMT_OFB_ETH_SRC, &headerFields.src_mac);
builder->setField(OFPXMT_OFB_IN_PORT, &headerFields.inport);
builder->setField(OFPXMT_OFB_VLAN_PCP,&vlanpcp);
oxm_basic_match match = builder->build();
return match;
}
else
{
return AVBLearningControllerApp::createMatchFromPacketIn(packetIn);
}
}
void TSNLearningControllerApp::processPacketIn(OFP_Packet_In* packet_in_msg)
{
if(CoRE4INET::EthernetIIFrameWithQTag* qframe = dynamic_cast<CoRE4INET::EthernetIIFrameWithQTag *>(packet_in_msg->getEncapsulatedPacket()))
{
for(int staticPriority: _staticPriorities){
if(qframe->getPcp() == staticPriority){
dropPacket(packet_in_msg);
return;
}
}
}
AVBLearningControllerApp::processPacketIn(packet_in_msg);
}
} /*end namespace SDN4CoRE*/
| 2,691
|
C++
|
.cc
| 63
| 37.857143
| 143
| 0.734351
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,199
|
AVBSecurityControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/avb/AVBSecurityControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/controllerApps/avb/AVBSecurityControllerApp.h>
//inet
#include <inet/common/ModuleAccess.h>
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/transportlayer/contract/ITransportPacket.h"
//AUTO_GENERATED MESSAGES
#include "inet/networklayer/arp/ipv4/ARPPacket_m.h"
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//AUTO_GENERATED MESSAGES
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
//openflow
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
namespace SDN4CoRE {
using namespace inet;
using namespace std;
using namespace CoRE4INET;
using namespace openflow;
Define_Module(AVBSecurityControllerApp);
AVBSecurityControllerApp::AVBSecurityControllerApp() : AVBLearningControllerApp(){
}
AVBSecurityControllerApp::~AVBSecurityControllerApp() {
}
void AVBSecurityControllerApp::initialize() {
AVBLearningControllerApp::initialize();
setState(OK);
_trafficLight = getModuleFromPar<ColorChangingNode>(par("pathToTrafficLight"), this, false);
}
void AVBSecurityControllerApp::handleParameterChange(const char* parname)
{
AVBLearningControllerApp::handleParameterChange(parname);
if (!parname || !strcmp(parname, "NADSPort"))
{
_NADSPort = par("NADSPort");
}
if (!parname || !strcmp(parname, "controllerMAC"))
{
_controllerMAC.setAddress(par("controllerMAC").stringValue());
}
if (!parname || !strcmp(parname, "allowNewFlows"))
{
_allowNewFlows = par("allowNewFlows").boolValue();
}
if (!parname || !strcmp(parname, "allowNewFlows"))
{
_allowARP = par("allowARP").boolValue();
}
if (!parname || !strcmp(parname, "allowNewFlows"))
{
_allowSRP = par("allowSRP").boolValue();
}
}
void AVBSecurityControllerApp::handleMessage(cMessage* msg) {
if(msg->isSelfMessage() && !strcmp(msg->getName(), "AnomalyTimeout")){
//reset the message scheduled value as we just received one.
_anomalyScheduled = false;
//check if this is the last anomaly that happened and no anomalys happend aftwerwards.
if((_lastAnomaly + _anomalyTimeout <= simTime()) && (_anomalyCount == 0)){
setState(WARNING);
} else {
scheduleSelfMessage();
}
}
if(msg)
delete msg;
}
void AVBSecurityControllerApp::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj, cObject* details) {
bool forwardToBase = true;
if (id == PacketInSignalId) {
if (OFP_Packet_In *packet_in = dynamic_cast<OFP_Packet_In *>(obj)) {
if (dynamic_cast<EthernetIIFrame *>(packet_in->getEncapsulatedPacket())) {
CommonHeaderFields headerFields = extractCommonHeaderFields(packet_in);
//check if NADSPort is set
if(_NADSPort > NADS_PORT_NONE && headerFields.inport == _NADSPort){
//do not forward this as it is for the security module.
forwardToBase = false;
handleNADSMessage(packet_in);
}
}
#if OFP_VERSION_IN_USE == OFP_100
if(packet_in->getReason() == OFPR_NO_MATCH)
{// Flow is unknown by switch. Check if it is in our whitelist
if(!isWhitelisted(packet_in)){
// do not forward this flow.
if(_state < WARNING)
this->setState(WARNING);
forwardToBase = false;
}
}
#endif
}
}
if(id == PacketFeatureReplySignalId){
//new switch is connected implement flow for NADS -> Controller, if NADS is active.
if(_NADSPort > NADS_PORT_NONE){
if (Open_Flow_Message *msg = dynamic_cast<Open_Flow_Message *>(obj)) {
handleNewSwitch(msg);
}
}
}
if(forwardToBase) {
AVBLearningControllerApp::receiveSignal(src, id, obj, details);
}
}
void AVBSecurityControllerApp::refreshDisplay() const {
if (_stateUpdated){
if(_trafficLight){
switch (_state){
case NONE:
break;
case OK:
_trafficLight->setColor("green");
break;
case WARNING:
_trafficLight->setColor("yellow");
break;
case DANGER:
_trafficLight->setColor("red");
break;
default:
break;
}
}
_stateUpdated = false;
}
}
oxm_basic_match AVBSecurityControllerApp::createMatchFromPacketIn(
OFP_Packet_In* packetIn) {
oxm_basic_match match;
if (packetIn->getBuffer_id() == OFP_NO_BUFFER){
auto builder = OFMatchFactory::getBuilder();
// we got the full packet.
int in_port = packetIn->getEncapsulatedPacket()->getArrivalGate()->getIndex();
builder->setField(OFPXMT_OFB_IN_PORT, &in_port);
if(EthernetIIFrame * frame = dynamic_cast<EthernetIIFrame *>(packetIn->getEncapsulatedPacket())){
auto mac_src = frame->getSrc();
builder->setField(OFPXMT_OFB_ETH_SRC, &mac_src);
auto mac_dest = frame->getDest();
builder->setField(OFPXMT_OFB_ETH_DST, &mac_dest);
//check if the frame has Q extensions.
if(AVBFrame * avbFrame = dynamic_cast<AVBFrame *>(frame)){
uint16_t avb_type = 0x8100;
builder->setField(OFPXMT_OFB_ETH_TYPE, &avb_type);
auto vlan_vid = avbFrame->getVID();
builder->setField(OFPXMT_OFB_VLAN_VID, &vlan_vid);
auto vlan_pcp = avbFrame->getPcp();
builder->setField(OFPXMT_OFB_VLAN_PCP, &vlan_pcp);
} else {
uint16_t eth_type = frame->getEtherType();
builder->setField(OFPXMT_OFB_ETH_TYPE, ð_type);
}
if(ARPPacket *arpPacket = dynamic_cast<ARPPacket *>(frame->getEncapsulatedPacket()))
{//ARP packet. --> frame->getEtherType() == EtherType::ETHERTYPE_ARP
//TODO fix --> no rules for arp!
uint8_t iproto = arpPacket->getOpcode();
builder->setField(OFPXMT_OFB_IP_PROTO, &iproto);
auto ip_src = arpPacket->getSrcIPAddress();
builder->setField(OFPXMT_OFB_IPV4_SRC, &ip_src);
auto ip_dst = arpPacket->getDestIPAddress();
builder->setField(OFPXMT_OFB_IPV4_SRC, &ip_dst);
}
else if(IPv4Datagram * ipv4Datagram = dynamic_cast<IPv4Datagram *>(frame->getEncapsulatedPacket()))
{//IPv4 --> frame->getEtherType() == EtherType::ETHERTYPE_IPv4
uint8_t iproto = ipv4Datagram->getTransportProtocol();
builder->setField(OFPXMT_OFB_IP_PROTO, &iproto);
auto ip_src = ipv4Datagram->getSourceAddress().toIPv4();
builder->setField(OFPXMT_OFB_IPV4_SRC, &ip_src);
auto ip_dst = ipv4Datagram->getSourceAddress().toIPv4();
builder->setField(OFPXMT_OFB_IPV4_SRC, &ip_dst);
if(ITransportPacket * transport = dynamic_cast<ITransportPacket *>(ipv4Datagram->getEncapsulatedPacket()))
{// Transport packet.
auto tp_src = transport->getSourcePort();
builder->setField(OFPXMT_OFB_TCP_SRC, &tp_src);
auto tp_dst = transport->getDestinationPort();
builder->setField(OFPXMT_OFB_TCP_DST, &tp_dst);
}
}
}
match = builder->build();
} else{
// we only have match so copy it.
match = packetIn->getMatch();
}
return match;
}
void AVBSecurityControllerApp::sendFlowModMessage(ofp_flow_mod_command mod_com,
const oxm_basic_match& match, uint32_t outport, inet::TCPSocket* socket,
int idleTimeOut, int hardTimeOut) {
EV << "sendFlowModMessage" << '\n';
numFlowMod++;
std::vector<int> outports;
outports.push_back(outport);
if(match.OFB_IN_PORT != _NADSPort && ((uint32_t)outport) != OFPP_CONTROLLER) {
checkOrAddNADSPort(&outports);
}
//fill int array
uint32_t out[outports.size()];
for(size_t i=0; i<outports.size(); i++) {
out[i] = outports[i];
}
OFP_Flow_Mod* flow_mod_msg = OFMessageFactory::instance()->createFlowModMessage(mod_com, match, 0, out, outports.size(), idleTimeOut, hardTimeOut);
socket->send(flow_mod_msg);
}
void AVBSecurityControllerApp::sendSRPFlowModMessage(ofp_flow_mod_command mod_com, const oxm_basic_match &match, std::vector<int> outports, TCPSocket * socket, int idleTimeOut =1 , int hardTimeOut=0){
EV << "sendFlowModMessage" << '\n';
numFlowMod++;
if(match.OFB_IN_PORT != _NADSPort) {
checkOrAddNADSPort(&outports);
}
//fill int array
uint32_t out[outports.size()];
for(size_t i=0; i<outports.size(); i++) {
out[i] = outports[i];
}
OFP_Flow_Mod* flow_mod_msg = OFMessageFactory::instance()->createFlowModMessage(mod_com, match, 5000, out, outports.size(), idleTimeOut, hardTimeOut);
socket->send(flow_mod_msg);
}
OFP_Packet_Out * AVBSecurityControllerApp::createPacketOutFromPacketIn(OFP_Packet_In *packet_in_msg, uint32_t outport){
OFP_Packet_Out *packetOut = nullptr;
std::vector<int> outports;
outports.push_back(outport);
int inport = packet_in_msg->getEncapsulatedPacket()->getArrivalGate()->getIndex();
if(inport != _NADSPort
&& ((uint32_t)outport) != OFPP_CONTROLLER) {
checkOrAddNADSPort(&outports);
}
//fill int array
uint32_t out[outports.size()];
for(size_t i=0; i<outports.size(); i++) {
out[i] = outports[i];
}
if (packet_in_msg->getBuffer_id() == OFP_NO_BUFFER){
EthernetIIFrame *frame = dynamic_cast<EthernetIIFrame *>(packet_in_msg->getEncapsulatedPacket());
if(frame){
packetOut = OFMessageFactory::instance()->createPacketOut(out, outports.size(), frame->getArrivalGate()->getIndex(), packet_in_msg->getBuffer_id(), frame);
} else {
throw cRuntimeError("RTSecurityControllerApp::createPacketOutFromPacketIn: OFP_NO_BUFFER was set but no frame was provided in packet in");
}
} else {
packetOut = OFMessageFactory::instance()->createPacketOut(out, outports.size(), packet_in_msg->getMatch().OFB_IN_PORT, packet_in_msg->getBuffer_id());
}
return packetOut;
}
void AVBSecurityControllerApp::handleNewSwitch(Open_Flow_Message* msg) {
// create ofp match
auto builder = OFMatchFactory::getBuilder();
builder->setField(OFPXMT_OFB_ETH_DST, &_controllerMAC);
builder->setField(OFPXMT_OFB_IN_PORT, &_NADSPort);
oxm_basic_match match = builder->build();
// find TCP socket.
TCPSocket * socket = controller->findSocketFor(msg);
// send new flow mod for NADS -> Controller connection.
sendFlowModMessage(OFPFC_ADD, match, OFPP_CONTROLLER, socket, 0, 0);
}
void AVBSecurityControllerApp::scheduleSelfMessage() {
//set timer for status reset
if (!_anomalyScheduled) {
if((_lastAnomaly + _anomalyTimeout) > simTime()){
cMessage* timeout = new cMessage("AnomalyTimeout");
this->take(timeout);
this->scheduleAt(_lastAnomaly + _anomalyTimeout, timeout);
_anomalyCount = 0;
_anomalyScheduled = true;
}
}
}
void AVBSecurityControllerApp::handleNADSMessage(OFP_Packet_In* msg) {
this->setState(DANGER);
_lastAnomaly = simTime();
_anomalyCount++;
#if OFP_VERSION_IN_USE == OFP_100
if(msg->getReason() == OFPR_NO_MATCH)
{//miss allthough a flow should be implemented.
//handle new switch.
handleNewSwitch(msg);
}
#endif
//TODO not always delete same flow :-P
//delete flow
//stats
TCPSocket * socket = controller->findSocketFor(msg);
numFlowMod++;
auto eth_type = 2048;
auto dst_mac = MACAddress("0A-00-00-00-00-03");
auto src_mac = MACAddress("0A-00-00-00-00-10");
auto ip_proto = 17;
auto ip_src = IPv4Address("192.168.0.1");
auto ip_dst = IPv4Address("192.168.0.13");
auto tp_src = 6666;
auto tp_dst = 6666;
auto builder = OFMatchFactory::getBuilder();
builder->setField(OFPXMT_OFB_ETH_DST, &dst_mac);
builder->setField(OFPXMT_OFB_ETH_TYPE, ð_type);
builder->setField(OFPXMT_OFB_ETH_SRC, &src_mac);
builder->setField(OFPXMT_OFB_IP_PROTO, &ip_proto);
builder->setField(OFPXMT_OFB_IPV4_SRC, &ip_src);
builder->setField(OFPXMT_OFB_IPV4_SRC, &ip_dst);
builder->setField(OFPXMT_OFB_TCP_SRC, &tp_src);
builder->setField(OFPXMT_OFB_TCP_DST, &tp_dst);
oxm_basic_match match = builder->build();
//create message and deliver
OFP_Flow_Mod* flow_mod_msg = OFMessageFactory::instance()->createFlowModMessage(OFPFC_DELETE, match, 0, NULL, 0, 0, 0);
socket->send(flow_mod_msg);
//set timer for status reset
scheduleSelfMessage();
}
void AVBSecurityControllerApp::finish(){
AVBLearningControllerApp::finish();
}
bool AVBSecurityControllerApp::checkOrAddNADSPort(std::vector<int>* portlist) {
bool updated = false;
bool containsNads = false;
if(_NADSPort > NADS_PORT_NONE){
for(auto iter = (*portlist).begin(); iter < (*portlist).end(); iter++){
if(_NADSPort == (*iter)) {
containsNads = true;
break;
}
}
if(!containsNads) {
(*portlist).push_back(_NADSPort);
updated = true;
}
}
return updated;
}
bool AVBSecurityControllerApp::isWhitelisted(OFP_Packet_In* packetIn) {
bool whitelisted = _allowNewFlows;
if(EthernetIIFrame *frame = dynamic_cast<EthernetIIFrame *>(packetIn->getEncapsulatedPacket())){
if(frame->getEtherType() == EtherType::ETHERTYPE_ARP){
//allow arp?
whitelisted = _allowARP;
}
} else if (dynamic_cast<CoRE4INET::SRPFrame *>(packetIn->getEncapsulatedPacket())){
whitelisted = _allowSRP;
}
return whitelisted;
}
} /* namespace SDN4CoRE */
| 15,057
|
C++
|
.cc
| 359
| 34.144847
| 200
| 0.640328
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,200
|
AVBLearningControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/avb/AVBLearningControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "sdn4core/controllerApps/avb/AVBLearningControllerApp.h"
#include "sdn4core/utility/dynamicmodules/DynamicModuleHandling.h"
//STD
#include <sstream>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
//CoRE4INET
#include "core4inet/base/avb/AVBDefs.h"
//AUTO_GENERATED MESSAGES
#include "core4inet/linklayer/ethernet/avb/AVBFrame_m.h"
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
#include "core4inet/linklayer/contract/ExtendedIeee802Ctrl_m.h"
//openflow
#include "openflow/messages/OFP_Flow_Mod_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/controller/OF_Controller.h"
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
using namespace inet;
using namespace CoRE4INET;
using namespace std;
using namespace openflow;
namespace SDN4CoRE{
Define_Module(AVBLearningControllerApp);
const char AVBLearningControllerApp::SRPTABLEMANAGERMODULEPATH[] = "sdn4core.controllerState.srp.SRPTableManagement";
void AVBLearningControllerApp::initialize() {
LearningControllerApp::initialize();
// try to locate the macTableManager
_srpManager = tryLocateStateManager<SRPTableManagement*>("srpTableManagement");
if(!_srpManager) {
// create the mac manager
_srpManager = dynamic_cast<SRPTableManagement*>(
createFinalizeAndScheduleDynamicModule(SRPTABLEMANAGERMODULEPATH,
"srpTableManagement", this->getParentModule()->getSubmodule("controllerState"), false));
if(!_srpManager){
throw cRuntimeError("Could not create SRPTableManagement.");
}
}
}
void AVBLearningControllerApp::processPacketIn(OFP_Packet_In* packet_in_msg) {
if (dynamic_cast<CoRE4INET::SRPFrame *>(packet_in_msg->getEncapsulatedPacket())) {
doSRP(packet_in_msg);
} else if (dynamic_cast<CoRE4INET::AVBFrame *>(packet_in_msg->getEncapsulatedPacket())) {
// do nothing because the rule should be implemented allready.
//throw cRuntimeError("Controller Received AVB Frame, this should never happen.");
} else {
LearningControllerApp::processPacketIn(packet_in_msg);
}
}
void AVBLearningControllerApp::doSRP(OFP_Packet_In* packet_in_msg) {
bool updated = true;
Switch_Info * swInfo = controller->findSwitchInfoFor(packet_in_msg);
int arrivalPort = packet_in_msg->getMatch().OFB_IN_PORT;
//get SRP Frame
if (CoRE4INET::SRPFrame * srpFrame =
dynamic_cast<CoRE4INET::SRPFrame *>(packet_in_msg->getEncapsulatedPacket())) {
if (CoRE4INET::TalkerAdvertise* talkerAdvertise =
dynamic_cast<CoRE4INET::TalkerAdvertise*>(srpFrame)) {
updated = _srpManager->registerTalker(swInfo, arrivalPort, talkerAdvertise);
//save talker and do nothing else.
} else if (CoRE4INET::ListenerReady* listenerReady =
dynamic_cast<CoRE4INET::ListenerReady*>(srpFrame)) {
//save listener
updated = _srpManager->registerListener(swInfo, arrivalPort, listenerReady);
if (updated) {
SRPTableManagement::SRPForwardingInfo_t* fwd = _srpManager->getForwardingInfoForStreamID (swInfo, listenerReady->getStreamID(), listenerReady->getVlan_identifier());
auto builder = OFMatchFactory::getBuilder();
builder->setField(OFPXMT_OFB_IN_PORT, &fwd->inPort);
builder->setField(OFPXMT_OFB_ETH_DST, &fwd->dest);
uint16_t avb_type = 0x8100;
builder->setField(OFPXMT_OFB_ETH_TYPE, &avb_type);
builder->setField(OFPXMT_OFB_VLAN_VID, &fwd->vlanID);
builder->setField(OFPXMT_OFB_VLAN_PCP, &fwd->pcp);
oxm_basic_match match = builder->build();
TCPSocket * socket = controller->findSocketFor(packet_in_msg);
sendSRPFlowModMessage(OFPFC_ADD, match, fwd->outports, socket, this->getIdleTimeout(), this->getHardTimeout());
delete fwd;
}
}
//forward original to the switch it came from.
forwardSRPPacket(packet_in_msg);
}
}
void AVBLearningControllerApp::sendSRPFlowModMessage(ofp_flow_mod_command mod_com, const oxm_basic_match &match, std::vector<int> outports, TCPSocket * socket, int idleTimeOut =0 , int hardTimeOut=0){
EV << "sendFlowModMessage" << '\n';
numFlowMod++;
int numOutPorts = outports.size();
uint32_t out[numOutPorts];
for(int i=0; i<numOutPorts; i++) {
out[i] = outports[i];
}
OFP_Flow_Mod* flow_mod_msg = OFMessageFactory::instance()->createFlowModMessage(mod_com, match, 5000, out, numOutPorts, idleTimeOut, hardTimeOut);
socket->send(flow_mod_msg);
}
void AVBLearningControllerApp::forwardSRPPacket(OFP_Packet_In* packet_in_msg) {
TCPSocket *socket = controller->findSocketFor(packet_in_msg);
//TODO use experimenter message instead of packet out!
OFP_Packet_Out *packetOut = new OFP_Packet_Out("forwardSRP");
ofp_header header = packetOut->getHeader();
header.version = OFP_VERSION;
header.type = OFPT_FLOW_MOD;
#if OFP_VERSION_IN_USE == OFP_100
header.type = OFPT_VENDOR;
// TODO Add Experimenter Message Structure!
#elif OFP_VERSION_IN_USE == OFP_151
header.type = OFPT_EXPERIMENTER;
// TODO Add Experimenter Message Structure!
#endif
packetOut->setHeader(header);
packetOut->setBuffer_id(packet_in_msg->getBuffer_id());
packetOut->setByteLength(24);
omnetpp::cPacket* packet = packet_in_msg->getEncapsulatedPacket();
//check if srp packet and copy it.
//forward to controller
CoRE4INET::SRPFrame* toSwtich = dynamic_cast<CoRE4INET::SRPFrame *>(packet->dup());
packetOut->encapsulate(toSwtich);
packetOut->setIn_port(packet_in_msg->getMatch().OFB_IN_PORT);
socket->send(packetOut);
}
bool AVBLearningControllerApp::loadOfflineConfigFromXML(Switch_Info* info) {
Enter_Method("loadOfflineConfigFromXML()");
//load XML config if specified.
bool changed = false;
cXMLElement* xmlDoc = par("configXML").xmlValue();
if(xmlDoc)
{//we got an XML document for config set.
changed |= LearningControllerApp::loadOfflineConfigFromXML(info);
changed |= _srpManager->loadConfigForSwitch(info->getMacAddress(), xmlDoc);
}
return changed;
}
std::string AVBLearningControllerApp::stateToXML() {
ostringstream oss;
string tab = "\t";
oss << "<controller>" << endl;
hostTable->dumpConfigToStream(oss, 2);
_srpManager->dumpConfigToStream(oss, 2);
oss << "</controller>" << endl;
return oss.str();
}
} /*end namespace SDN4CoRE*/
| 7,385
|
C++
|
.cc
| 157
| 41.280255
| 200
| 0.710344
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,201
|
PacketProcessorBase.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/base/PacketProcessorBase.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "PacketProcessorBase.h"
//STD
#include <fstream>
#include <sstream>
#include <algorithm>
#include <stdlib.h>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/transportlayer/contract/ITransportPacket.h"
//openflow
#include "openflow/messages/OFP_Flow_Mod_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
//CoRE4INET
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
#include "core4inet/utilities/customWatch.h"
using namespace inet;
using namespace std;
using namespace openflow;
using namespace CoRE4INET;
namespace SDN4CoRE {
simsignal_t PacketProcessorBase::packetFilteredSignal = registerSignal("packetFiltered");
simsignal_t PacketProcessorBase::packetProcessedSignal = registerSignal("packetProcessed");
void PacketProcessorBase::PacketFilter::initializeFromPar(
const string& parameterValue) {
this->clear();
// remove spaces
string parameter = parameterValue;
parameter.erase(remove(parameter.begin(), parameter.end(), ' '),
parameter.end());
cStringTokenizer listTokens(parameter.c_str(), ";");
while (listTokens.hasMoreTokens()) {
cStringTokenizer filterTokens(listTokens.nextToken(), "=");
string key = filterTokens.nextToken();
vector<string> values =
cStringTokenizer(filterTokens.nextToken(), ",").asVector();
// check inputs are valid syntax.
if (key.empty()) {
throw cRuntimeError(
"packetFilterList syntax error: Could not parse filter with empty key");
}
if (values.empty()) {
throw cRuntimeError(
"packetFilterList syntax error: Could not parse filter with empty value");
}
// further checks would require detailed knowledge about key and value...
// TODO should we implement further checks here to not throw runtime errors?
// insert it into the map
(*this)[key] = values;
}
}
bool PacketProcessorBase::PacketFilter::addPacketFilter(std::string key,
std::string value) {
vector<string>values;
values.push_back(value);
return addPacketFilters(key, values);
}
bool PacketProcessorBase::PacketFilter::addPacketFilters(std::string key,
vector<string> values) {
bool changed = false;
if (!values.empty() && !key.empty()) {
auto found = this->find(key);
if (found != this->end()) {
for (string existingValue : (*this)[key]) {
if(std::find(values.begin(), values.end(), existingValue) == values.end()) {
values.push_back(existingValue);
}
}
if(values.size() > (*this)[key].size()) {
changed = true;
}
} else {
changed = true;
}
(*this)[key] = values;
}
return changed;
}
bool PacketProcessorBase::PacketFilter::matchesIntValue(string key, int value) {
auto iter = this->find(key);
if (iter != this->end()) {
for (const string& strVal : iter->second) {
if (strtol(strVal.c_str(), NULL, 0) == value) {
return true;
}
}
}
return false;
}
bool PacketProcessorBase::PacketFilter::matchesStringValue(string key,
string value) {
auto iter = this->find(key);
if (iter != this->end()) {
for (const string& strVal : iter->second) {
if (strVal == value) {
return true;
}
}
}
return false;
}
bool PacketProcessorBase::PacketFilter::matchesMACAddressValue(string key,
MACAddress value) {
return matchesL3AddressValue(key, value);
}
bool PacketProcessorBase::PacketFilter::matchesL3AddressValue(string key,
L3Address value) {
auto iter = this->find(key);
if (iter != this->end()) {
for (const string& strVal : iter->second) {
vector<string> tokenized =
cStringTokenizer(strVal.c_str(), "/").asVector();
if (tokenized.size() > 2 || tokenized.size() < 1) {
throw cRuntimeError(
"Try parsing IP address from value %s but it does not match pattern IP[/mask]",
strVal.c_str());
}
L3Address addrVal(tokenized[0].c_str());
if (addrVal.isUnspecified()) {
throw cRuntimeError("Could not parse L3address from %s",
tokenized[0].c_str());
}
int prefixLength = 0;
if (tokenized.size() == 2) {
prefixLength = atoi(tokenized[1].c_str());
} else if (addrVal.getType() == L3Address::AddressType::IPv4) {
prefixLength = 32;
} else if (addrVal.getType() == L3Address::AddressType::IPv6) {
prefixLength = 128;
}
if (value.matches(addrVal, prefixLength)) {
return true;
}
}
}
return false;
}
bool PacketProcessorBase::PacketFilter::matchesPacketIn(
openflow::OFP_Packet_In* packet_in_msg) {
//physical info
//TODO check device id and in port
//layer 2
if (EthernetIIFrame* eth =
dynamic_cast<EthernetIIFrame *>(packet_in_msg->getEncapsulatedPacket())) {
if (matchesL3AddressValue("ethSrc", eth->getSrc())) {
return true;
}
if (matchesL3AddressValue("ethDst", eth->getDest())) {
return true;
}
if (matchesIntValue("etherType", eth->getEtherType())) {
return true;
}
//qframe
if (EthernetIIFrameWithQTag* vlan =
dynamic_cast<EthernetIIFrameWithQTag *>(packet_in_msg->getEncapsulatedPacket())) {
if (matchesIntValue("vlanId", vlan->getVID())) {
return true;
}
if (matchesIntValue("vlanPcp", vlan->getPcp())) {
return true;
}
}
//layer 3
if (INetworkDatagram* ip =
dynamic_cast<INetworkDatagram *>(eth->getEncapsulatedPacket())) {
int ipProto = ip->getTransportProtocol();
if (matchesIntValue("ipProto", ipProto)) {
return true;
}
if (matchesL3AddressValue("ipSrc", ip->getSourceAddress())) {
return true;
}
if (matchesL3AddressValue("ipDst", ip->getDestinationAddress())) {
return true;
}
//layer 4
if (ITransportPacket* transport =
dynamic_cast<ITransportPacket*>(eth->getEncapsulatedPacket()->getEncapsulatedPacket())) {
if (ipProto == IPProtocolId::IP_PROT_UDP) {
if (matchesIntValue("udpSrc", transport->getSourcePort())) {
return true;
}
if (matchesIntValue("udpDst",
transport->getDestinationPort())) {
return true;
}
} else if (ipProto == IPProtocolId::IP_PROT_TCP) {
if (matchesIntValue("tcpSrc", transport->getSourcePort())) {
return true;
}
if (matchesIntValue("tcpDst",
transport->getDestinationPort())) {
return true;
}
}
}
}
}
return false;
}
void PacketProcessorBase::initialize() {
AbstractControllerApp::initialize();
WATCH_LISTMAP(_whitelist);
WATCH_LISTMAP(_blacklist);
}
void PacketProcessorBase::handleParameterChange(const char* parname) {
AbstractControllerApp::handleParameterChange(parname);
if (!parname || !strcmp(parname, "flowModIdleTimeOut")) {
_idleTimeout = par("flowModIdleTimeOut");
}
if (!parname || !strcmp(parname, "flowModHardTimeOut")) {
_hardTimeout = par("flowModHardTimeOut");
}
if (!parname || !strcmp(parname, "packetFilterWhitelist")) {
_whitelist.initializeFromPar(
this->par("packetFilterWhitelist").stdstringValue());
}
if (!parname || !strcmp(parname, "packetFilterBlacklist")) {
_blacklist.initializeFromPar(
this->par("packetFilterBlacklist").stdstringValue());
}
}
void PacketProcessorBase::receiveSignal(cComponent* src, simsignal_t id,
cObject* obj, cObject* details) {
if (id == PacketInSignalId) {
if (OFP_Packet_In *packet_in = dynamic_cast<OFP_Packet_In *>(obj)) {
if (!isFiltered(packet_in)) {
processPacketIn(packet_in);
emit(packetProcessedSignal,packet_in);
} else {
emit(packetFilteredSignal,packet_in);
}
}
} else if (id == PacketFeatureReplySignalId) {
if (Open_Flow_Message *msg = dynamic_cast<Open_Flow_Message *>(obj)) {
//new switch registered check if we allready got a offline config for it.
processSwitchConnection(controller->findSwitchInfoFor(msg));
}
} else {
AbstractControllerApp::receiveSignal(src, id, obj, details);
}
}
void PacketProcessorBase::finish() {
AbstractControllerApp::finish();
string filename = par("dumpConfig").stdstringValue();
if (!filename.empty()) {
ofstream file;
file.open(filename.c_str(), ios::app);
if (!file.is_open())
throw cRuntimeError("Cannot open output file");
file << stateToXML();
file.close();
}
}
bool PacketProcessorBase::isFiltered(openflow::OFP_Packet_In* packet_in_msg) {
if (_whitelist.empty() || _whitelist.matchesPacketIn(packet_in_msg)) {
if (_blacklist.empty() || !_blacklist.matchesPacketIn(packet_in_msg)) {
return false;
}
}
return true;
}
} /*end namespace SDN4CoRE*/
| 10,796
|
C++
|
.cc
| 280
| 29.571429
| 109
| 0.603907
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,202
|
LearningControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/base/LearningControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "sdn4core/controllerApps/base/LearningControllerApp.h"
#include "sdn4core/utility/dynamicmodules/DynamicModuleHandling.h"
//STD
#include <sstream>
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#include "inet/transportlayer/contract/ITransportPacket.h"
//openflow
#include "openflow/messages/OFP_Flow_Mod_m.h"
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
//CoRE4INET
#include "core4inet/linklayer/ethernet/base/EtherFrameWithQTag_m.h"
using namespace inet;
using namespace std;
using namespace openflow;
using namespace CoRE4INET;
namespace SDN4CoRE {
Define_Module(LearningControllerApp);
void LearningControllerApp::initialize() {
PacketProcessorBase::initialize();
hostTable = check_and_cast<HostTable*>(
this->getModuleByPath(par("hostTablePath")));
deviceTable = check_and_cast<DeviceTable*>(
this->getModuleByPath(par("deviceTablePath")));
topology = check_and_cast<TopologyManagement*>(
this->getModuleByPath(par("topologyManagementPath")));
}
void LearningControllerApp::processPacketIn(OFP_Packet_In* packet_in_msg) {
Switch_Info* swInfo = controller->findSwitchInfoFor(packet_in_msg);
hostTable->update(packet_in_msg, swInfo);
//find outport or flood
int outport = topology->findOutportAtSwitch(swInfo, packet_in_msg);
if (outport == -1) {
floodPacket(packet_in_msg);
} else {
oxm_basic_match match = createMatchFromPacketIn(packet_in_msg);
TCPSocket * socket = controller->findSocketFor(packet_in_msg);
sendFlowModMessage(OFPFC_ADD, match, outport, socket, getIdleTimeout(),
getHardTimeout());
sendPacket(packet_in_msg, outport);
}
}
oxm_basic_match LearningControllerApp::createMatchFromPacketIn(
OFP_Packet_In* packetIn) {
if (packetIn->getBuffer_id() != OFP_NO_BUFFER){
// todo forward buffered packets.
throw cRuntimeError("Learning Controller does not yet support buffered packets.");
}
auto builder = OFMatchFactory::getBuilder();
if(par("matchAll").boolValue() || par("matchInport").boolValue()) {
int inport = packetIn->getEncapsulatedPacket()->getArrivalGate()->getIndex();
builder->setField(OFPXMT_OFB_IN_PORT, &inport);
}
//layer 2
if (EthernetIIFrame* eth =
dynamic_cast<EthernetIIFrame *>(packetIn->getEncapsulatedPacket())) {
if(par("matchAll").boolValue() || par("matchL2Src").boolValue()) {
MACAddress src = eth->getSrc();
builder->setField(OFPXMT_OFB_ETH_SRC, &src);
}
if(par("matchAll").boolValue() || par("matchL2Dest").boolValue()) {
MACAddress dest = eth->getDest();
builder->setField(OFPXMT_OFB_ETH_DST, &dest);
}
if(par("matchAll").boolValue() || par("matchL2Type").boolValue()) {
int type = eth->getEtherType();
builder->setField(OFPXMT_OFB_ETH_TYPE, &type);
}
//qframe
if (EthernetIIFrameWithQTag* vlan =
dynamic_cast<EthernetIIFrameWithQTag *>(packetIn->getEncapsulatedPacket())) {
if(par("matchAll").boolValue() || par("matchL2VID").boolValue()) {
uint16_t vid = vlan->getVID();
builder->setField(OFPXMT_OFB_VLAN_VID, &vid);
}
if(par("matchAll").boolValue() || par("matchL2PCP").boolValue()) {
uint8_t pcp = vlan->getPcp();
builder->setField(OFPXMT_OFB_VLAN_PCP, &pcp);
}
}
//layer 3
if (INetworkDatagram* ip =
dynamic_cast<INetworkDatagram *>(eth->getEncapsulatedPacket())) {
if(par("matchAll").boolValue() || par("matchL3Src").boolValue()) {
IPv4Address src = ip->getSourceAddress().toIPv4();
builder->setField(OFPXMT_OFB_IPV4_SRC, &src);
}
if(par("matchAll").boolValue() || par("matchL3Dest").boolValue()) {
IPv4Address dest = ip->getDestinationAddress().toIPv4();
builder->setField(OFPXMT_OFB_IPV4_DST, &dest);
}
if(par("matchAll").boolValue() || par("matchL3Proto").boolValue()) {
int ipProto = ip->getTransportProtocol();
builder->setField(OFPXMT_OFB_IP_PROTO, &ipProto);
}
//layer 4
if (ITransportPacket* transport = dynamic_cast<ITransportPacket*>(eth->getEncapsulatedPacket()->getEncapsulatedPacket())) {
// ports are handled the same for tcp and udp depending on the ip proto type.
if(par("matchAll").boolValue() || par("matchL4Src").boolValue()) {
int src = transport->getSourcePort();
builder->setField(OFPXMT_OFB_UDP_SRC, &src);
}
if(par("matchAll").boolValue() || par("matchL4Dest").boolValue()) {
int dest = transport->getDestinationPort();
builder->setField(OFPXMT_OFB_UDP_DST, &dest);
}
}
}
}
return builder->build();
}
bool LearningControllerApp::loadOfflineConfigFromXML(Switch_Info* info) {
Enter_Method
("loadOfflineConfigFromXML()");
//load XML config if specified.
bool changed = false;
cXMLElement* xmlDoc = par("configXML").xmlValue();
if (xmlDoc) { //we got an XML document for config set.
changed |= hostTable->loadConfigForSwitch(info->getMacAddress(),
xmlDoc);
changed |= deviceTable->loadConfigForSwitch(info->getMacAddress(),
xmlDoc);
changed |= topology->loadConfigForSwitch(info->getMacAddress(),
xmlDoc);
}
return changed;
}
void LearningControllerApp::processSwitchConnection(
openflow::Switch_Info* info) {
deviceTable->addNetworkDevice(info);
PacketProcessorBase::processSwitchConnection(info);
}
string LearningControllerApp::stateToXML() {
ostringstream oss;
string tab = "\t";
oss << "<controller>" << endl;
hostTable->dumpConfigToStream(oss, 2);
deviceTable->dumpConfigToStream(oss, 2);
topology->dumpConfigToStream(oss, 2);
oss << "</controller>" << endl;
return oss.str();
}
} /*end namespace SDN4CoRE*/
| 7,129
|
C++
|
.cc
| 162
| 36.41358
| 135
| 0.654156
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,203
|
LLDPControllerApp.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerApps/lldp/LLDPControllerApp.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "sdn4core/controllerApps/lldp/LLDPControllerApp.h"
//inet
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
//openflow
#include "openflow/openflow/protocol/OFMessageFactory.h"
#include "openflow/openflow/protocol/OFMatchFactory.h"
#include "openflow/messages/LLDP_m.h"
#define LLDP_ETHER_TYPE 0x88CC
using namespace inet;
using namespace std;
using namespace openflow;
namespace SDN4CoRE {
Define_Module(LLDPControllerApp);
void LLDPControllerApp::initialize() {
PacketProcessorBase::initialize();
deviceTable = check_and_cast<DeviceTable*>(
this->getModuleByPath(par("deviceTablePath")));
trigger = new cMessage("LLDP Trigger Message");
}
void LLDPControllerApp::handleParameterChange(const char* parname) {
PacketProcessorBase::handleParameterChange(parname);
if (!parname || !strcmp(parname, "cycle")) {
cycle = par("cycle");
}
if (!parname || !strcmp(parname, "lldpOnNewConnection")) {
lldpOnNewConnection = par("lldpOnNewConnection");
}
}
void LLDPControllerApp::handleMessage(cMessage* msg) {
if (msg == this->trigger) {
EV << "Sending Link Layer Discovery through connected switches";
sendLLDP();
scheduleNextCycle();
} else {
PacketProcessorBase::handleMessage(msg);
}
}
void LLDPControllerApp::processPacketIn(OFP_Packet_In* packet_in_msg) {
// we should only receive Ethernet LLDP frames because of the packet processor!
if (EthernetIIFrame *eth =
dynamic_cast<EthernetIIFrame *>(packet_in_msg->getEncapsulatedPacket())) {
if (LLDP *lldp = dynamic_cast<LLDP *>(eth->getEncapsulatedPacket())) {
string outSwitchId = lldp->getChassisID();
int outport = lldp->getPortID();
string inSwitchId =
controller->findSwitchInfoFor(packet_in_msg)->getMacAddress();
int inport = eth->getArrivalGate()->getIndex();
deviceTable->linkNetworkDevices(outSwitchId, outport, inSwitchId,
inport);
} else {
throw cRuntimeError(
"The received Ethernet Frame does not contain LLDP");
}
} else {
throw cRuntimeError("Received a non Ethernet Frame");
}
}
void LLDPControllerApp::processSwitchConnection(openflow::Switch_Info* info) {
deviceTable->addNetworkDevice(info);
PacketProcessorBase::processSwitchConnection(info);
EV << "New switch connected, installing LLDP Flow";
installLLDPFLow(info);
if (lldpOnNewConnection) {
sendLLDP();
}
if(!this->trigger->isScheduled()) { // this is the first switch we have not yet started with lldp
scheduleNextCycle();
}
}
void LLDPControllerApp::scheduleNextCycle() {
Enter_Method_Silent
();
this->cancelEvent(this->trigger);
if (deviceTable->getDeviceCount() > 0) {
this->scheduleAt(simTime() + cycle, this->trigger);
EV << "Next LLDP cycle scheduled in " << cycle;
}
}
void LLDPControllerApp::installLLDPFLow(openflow::Switch_Info* swInfo) {
auto builder = OFMatchFactory::getBuilder();
uint16_t lldp_type = LLDP_ETHER_TYPE;
builder->setField(OFPXMT_OFB_ETH_TYPE, &lldp_type);
oxm_basic_match match = builder->build();
sendFlowModMessage(OFPFC_ADD, match, OFPP_CONTROLLER, swInfo->getSocket(),
0, 0);
}
void LLDPControllerApp::sendLLDP() {
for (auto& device : *(controller->getSwitchesList())) {
if (strcmp(device.getMacAddress().c_str(), "") == 0) {
//only use full connections
continue;
}
sendLLDP(&device);
}
}
void LLDPControllerApp::sendLLDP(openflow::Switch_Info* swInfo) {
if (swInfo) {
for (int i = 0; i < swInfo->getNumOfPorts(); i++) {
EthernetIIFrame* lldp = createLLDPPacket(swInfo->getMacAddress(),
i);
uint32_t ports[] = { (uint32_t) i };
OFP_Packet_Out* packetOut =
OFMessageFactory::instance()->createPacketOut(ports, 1, -1,
OFP_NO_BUFFER, lldp);
controller->sendPacketOut(packetOut, swInfo->getSocket());
delete lldp;
}
}
}
EthernetIIFrame* LLDPControllerApp::createLLDPPacket(string switchId,
int port) {
LLDP *lldpPacket = new LLDP("LLDP");
lldpPacket->setPortID(port);
lldpPacket->setChassisID(switchId.c_str());
EthernetIIFrame *eth = new EthernetIIFrame(lldpPacket->getName());
eth->setSrc(MACAddress(switchId.c_str()));
//eth->setDest(MACAddress("01:80:c2:00:00:0e"));
//make up an address as inet will accept multicast frames and does not know what to do with a lldp frame and thus fails
eth->setDest(MACAddress("AA:80:c2:00:00:0e"));
eth->setEtherType(LLDP_ETHER_TYPE);
eth->encapsulate(lldpPacket);
if (eth->getByteLength() < MIN_ETHERNET_FRAME_BYTES) {
eth->setByteLength(MIN_ETHERNET_FRAME_BYTES); // "padding"
}
return eth;
}
} /*end namespace SDN4CoRE*/
| 5,723
|
C++
|
.cc
| 143
| 34.062937
| 123
| 0.678353
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,204
|
XMLUtility.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/xml/XMLUtility.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "XMLUtility.h"
using namespace std;
namespace SDN4CoRE {
/**
* Helper method to get a string attribute from an XML config.
* @return the value from xml if present, the alternative value if the parameter is not required.
* @throw a runtime error if required is true and attribute cannot be found.
*/
std::string getStringAttributeFromXML(cXMLElement* configureXML,
const char* attribute, bool required, std::string alternativeValue) {
const char* parameter = configureXML->getAttribute(attribute);
if (required && parameter == nullptr) {
throw cRuntimeError("Could not parse XML input for controller application because required attribute %s does not exist", attribute);
}
return ((parameter != nullptr) ? parameter : alternativeValue);
}
/**
* Helper method to get a string attribute from an XML config.
* @return the value from xml if present, the alternative value if the parameter is not required.
* @throw a runtime error if required is true and attribute cannot be found.
*/
int getIntAttributeFromXML(cXMLElement* configureXML,
const char* attribute, bool required, int alternativeValue) {
const char* parameter = configureXML->getAttribute(attribute);
if (required && parameter == nullptr) {
throw cRuntimeError("Could not parse XML input for controller application because required attribute %s does not exist", attribute);
}
return ((parameter != nullptr) ? atoi(parameter) : alternativeValue);
}
/**
* Helper method to get a string attribute from an XML config.
* @return the value from xml if present, the alternative value if the parameter is not required.
* @throw a runtime error if required is true and attribute cannot be found.
*/
double getDoubleAttributeFromXML(cXMLElement* configureXML,
const char* attribute, bool required, double alternativeValue) {
const char* parameter = configureXML->getAttribute(attribute);
if (required && parameter == nullptr) {
throw cRuntimeError("Could not parse XML input for controller application because required attribute %s does not exist", attribute);
}
return ((parameter != nullptr) ? stod(parameter) : alternativeValue);
}
}; // namespace SDN4CoRE
| 2,946
|
C++
|
.cc
| 59
| 46.915254
| 140
| 0.754172
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,205
|
ProcessingTimeSimulation.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/processing/ProcessingTimeSimulation.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "ProcessingTimeSimulation.h"
namespace SDN4CoRE{
#define MSGKIND_SERVICETIME 3
ProcessingTimeSimulation::~ProcessingTimeSimulation() {
for(auto&& entry : _msgList) {
delete entry;
}
_msgList.clear();
}
void ProcessingTimeSimulation::initialize()
{
handleParameterChange(nullptr);
_queueSize = registerSignal("queueSize");
_waitingTime = registerSignal("waitingTime");
_busy = false;
}
void ProcessingTimeSimulation::handleParameterChange(const char* parname) {
if (!parname || !strcmp(parname, "processingTime")) {
_processingTime = par("processingTime");
}
if (!parname || !strcmp(parname, "allowParallelProcessing")) {
_allowParallelProcessing = par("allowParallelProcessing");
}
}
double ProcessingTimeSimulation::getProcessingTime(){
handleParameterChange("processingTime");
return _processingTime;
}
void ProcessingTimeSimulation::triggerNextProcessingTime() {
//Trigger next service time
if (_msgList.empty()) {
_busy = false;
} else {
cMessage* msgFromList = _msgList.front();
_msgList.pop_front();
cMessage* event = new cMessage("event");
event->setKind(MSGKIND_SERVICETIME);
event->setContextPointer(msgFromList);
scheduleAt(simTime() + getProcessingTime(), event);
}
}
void ProcessingTimeSimulation::handleMessage(cMessage *msg)
{
if (msg->isSelfMessage() && msg->getKind() == MSGKIND_SERVICETIME) {
// processing delay introduced now handle the message
cMessage* data_msg = (cMessage*) (msg->getContextPointer());
emit(_waitingTime, (simTime() - data_msg->getArrivalTime()));
processScheduledMessage(data_msg);
//Trigger next service time
triggerNextProcessingTime();
delete msg;
} else {
simulateProcessingTime(msg);
}
}
void ProcessingTimeSimulation::simulateProcessingTime(cMessage* msg) {
if (_busy && !_allowParallelProcessing) {
_msgList.push_back(msg);
} else {
_busy = true;
cMessage* event = new cMessage("event");
event->setKind(MSGKIND_SERVICETIME);
event->setContextPointer(msg);
scheduleAt(simTime() + getProcessingTime(), event);
}
emit(_queueSize, static_cast<unsigned int>(_msgList.size()));
}
} /*end namespace SDN4CoRE*/
| 3,074
|
C++
|
.cc
| 84
| 32
| 78
| 0.703156
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,206
|
ColorChangingNode.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/visual/ColorChangingNode.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include "ColorChangingNode.h"
using namespace std;
using namespace omnetpp;
namespace SDN4CoRE {
Define_Module(ColorChangingNode);
void ColorChangingNode::initialize()
{
string initColor = par("initColor");
if(!initColor.empty()){
this->setColor(initColor);
}
string initOpacity = par("initOpacity");
if(!initOpacity.empty()){
this->setOpacity(initOpacity);
}
}
void ColorChangingNode::refreshDisplay() const {
if (_colorUpdated){
if (getEnvir()->isGUI()) {
getDisplayString().setTagArg("i", 1, _color.c_str());
getDisplayString().setTagArg("i", 2, _opacity.c_str());
}
_colorUpdated = false;
}
}
void ColorChangingNode::setColor(const std::string& color) {
this->_color = color;
_colorUpdated = true;
}
void ColorChangingNode::setOpacity(const std::string& opacity) {
this->_opacity = opacity;
_colorUpdated = true;
}
} // namespace SDN4CoRE
| 1,656
|
C++
|
.cc
| 50
| 29.66
| 71
| 0.70802
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,207
|
NodeDisplayEditor.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/visual/NodeDisplayEditor.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#include <sdn4core/utility/visual/NodeDisplayEditor.h>
using namespace omnetpp;
namespace SDN4CoRE {
NodeDisplayEditor::NodeDisplayEditor(cModule* targetModule) :
_target(targetModule) {
}
NodeDisplayEditor::~NodeDisplayEditor() {
}
void NodeDisplayEditor::setNodeColor(const char* color, const char* opacity) {
setNodeColor(_target, color, opacity);
}
void NodeDisplayEditor::setNodeColor(omnetpp::cModule* target,
const char* color, const char* opacity) {
if (target && getEnvir()->isGUI()) {
if (color && opacity) {
if (target->hasDisplayString()) {
target->getDisplayString().setTagArg("i", 1, color);
target->getDisplayString().setTagArg("i", 2, opacity);
}
}
}
}
NodeDisplayEditor::NodeDisplayEditor() :
_target(nullptr) {
}
} /* namespace SDN4CoRE */
| 1,566
|
C++
|
.cc
| 42
| 33.428571
| 78
| 0.712302
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,208
|
LayeredInformation.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/layeredInformation/LayeredInformation.cc
|
/*
* LayeredInformation.cc
*
* Created on: 13.09.2022
* Author: jsolb
*/
#include <sdn4core/utility/layeredInformation/LayeredInformation.h>
namespace SDN4CoRE {
LayeredInformation::LayeredInformation() {
// TODO Auto-generated constructor stub
}
void LayeredInformation::copy(const LayeredInformation& other) {
this->eth_src = other.eth_src;
this->eth_dst = other.eth_dst;
this->ip_src = other.ip_src;
this->ip_dst = other.ip_dst;
this->transport_src = other.transport_src;
this->transport_dst = other.transport_dst;
this->in_port = other.in_port;
this->sw_info = other.sw_info;
}
LayeredInformation::~LayeredInformation() {
}
} /* namespace SDN4CoRE */
| 742
|
C++
|
.cc
| 24
| 26.541667
| 68
| 0.693732
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,209
|
DynamicChannelParameterChanger.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/dynamicparameters/DynamicChannelParameterChanger.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/utility/dynamicparameters/DynamicChannelParameterChanger.h>
#include "inet/common/InitStages.h"
using namespace std;
using namespace inet;
namespace SDN4CoRE{
Define_Module(DynamicChannelParameterChanger);
void DynamicChannelParameterChanger::fillComponentToChange(vector<string>& paths){
for (string path : paths){
//resolve the module path
cModule* module = this->getModuleByPath(path.c_str());
if(!module) {
throw cRuntimeError("The channels connected module %s was not found", path.c_str());
}
//find the gate
string gateName = this->par("gateAtComponent");
if(gateName.empty()) {
throw cRuntimeError("Gate %s not specified", gateName.c_str());
}
if(!module->hasGate(gateName.c_str())){
throw cRuntimeError("Module %s has no gate named %s ", path.c_str(), gateName.c_str());
}
//check weather it is a vector and the full vector should be updated
int startIdx = this->par("gateIdx").intValue();
int gateSize = module->gateSize(gateName.c_str());
if(this->par("fullVector")) {
if(!module->isGateVector(gateName.c_str())) {
throw cRuntimeError("Changing the full vector is set but gate %s at module %s is no vector gate", gateName.c_str(), path.c_str());
}
startIdx = 0;
}
// add channels to components
for (int i = startIdx; i < gateSize; i++) {
vector<cComponent*> channels;
//find in and outbound channels
if(module->gateType(gateName.c_str()) == cGate::INOUT) {
channels.push_back(getChannelForGate(module->gateHalf(gateName.c_str(), cGate::INPUT, i)));
channels.push_back(getChannelForGate(module->gateHalf(gateName.c_str(), cGate::OUTPUT, i)));
} else {
channels.push_back(getChannelForGate(module->gate(gateName.c_str(), i)));
}
//add channels to components
for(auto channel : channels){
if(!channel){
throw cRuntimeError("Channel at gate %s with index %s in module %s", gateName.c_str(), to_string(i).c_str(), path.c_str());
}
if(!channel->hasPar(_parToChange.c_str())){
throw cRuntimeError("Channel at gate %s of module %s has no parameter named %s", gateName.c_str(), path.c_str(), _parToChange.c_str());
}
_componentsToChange[channel] = channel->par(_parToChange.c_str()).str();
}
//abort if not use full vector
if(!this->par("fullVector")) {
break;
}
}
}
}
cComponent* DynamicChannelParameterChanger::getChannelForGate(cGate* gate) {
cComponent* channel = nullptr;
cGate* inOrigin = nullptr;
switch(gate->getType()) {
case cGate::INPUT:
inOrigin = gate->getPreviousGate();
if(!inOrigin) {
throw cRuntimeError("Input gate %s in module %s seems unconnected", gate->getFullName(), gate->getOwner()->getFullName());
}
channel = dynamic_cast<cComponent*>(inOrigin->getChannel());
break;
case cGate::OUTPUT:
channel = dynamic_cast<cComponent*>(gate->getChannel());
break;
default:
break;
}
return channel;
}
} // namespace SDN4CoRE
| 4,101
|
C++
|
.cc
| 91
| 36.681319
| 155
| 0.628621
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,210
|
DynamicParameterChanger.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/dynamicparameters/DynamicParameterChanger.cc
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/utility/dynamicparameters/DynamicParameterChanger.h>
#include "inet/common/InitStages.h"
using namespace inet;
using namespace std;
namespace SDN4CoRE{
#define DPC_CHANGE_MSG_NAME "Change"
#define DPC_RESET_MSG_NAME "Reset"
Define_Module(DynamicParameterChanger);
int DynamicParameterChanger::numInitStages() const {
return NUM_INIT_STAGES;
}
void DynamicParameterChanger::fillComponentToChange(vector<string>& paths){
for (string path : paths){
//resolve the module path
cModule* module = this->getModuleByPath(path.c_str());
if(!module) {
throw cRuntimeError("Module %s not found", path.c_str());
}
cComponent* component = dynamic_cast<cComponent*>(module);
if(!component->hasPar(_parToChange.c_str())){
throw cRuntimeError("Module %s has no parameter named %s", path.c_str(), _parToChange.c_str());
}
_componentsToChange[component] = component->par(_parToChange.c_str()).str();
}
}
void DynamicParameterChanger::initialize(int stage)
{
if(stage == INITSTAGE_LAST) {
//buffer parameters
auto paths = cStringTokenizer(this->par("pathToComponentsToChange"), ";").asVector();
if (paths.empty()){
//abort if no modules set
return;
}
this->_parToChange = this->par("parToChange").stdstringValue();
if(_parToChange.empty()) {
throw cRuntimeError("Parameter to change %s is empty", this->par("parToChange").str().c_str());
}
this->_newValue = this->par("newValue").stdstringValue();
if(_newValue.empty()) {
throw cRuntimeError("New value %s is empty", this->par("newValue").str().c_str());
}
fillComponentToChange(paths);
//schedule change and reset messages
scheduleAt(this->par("changeAt").doubleValue(),new cMessage(DPC_CHANGE_MSG_NAME));
if(this->par("enableReset").boolValue()) {
scheduleAt(this->par("resetAt").doubleValue(),new cMessage(DPC_RESET_MSG_NAME));
}
}
}
void DynamicParameterChanger::handleMessage(cMessage *msg)
{
if(msg->isSelfMessage() && strcmp(msg->getName(), DPC_CHANGE_MSG_NAME) == 0){
changePars();
} else if(msg->isSelfMessage() && strcmp(msg->getName(), DPC_RESET_MSG_NAME) == 0){
resetPars();
}
delete msg;
}
void DynamicParameterChanger::changePars() {
for(auto component : _componentsToChange) {
_componentsToChange[component.first] = component.first->par(_parToChange.c_str()).str();
component.first->par(this->_parToChange.c_str()).parse(this->_newValue.c_str());
}
}
void DynamicParameterChanger::resetPars() {
for(auto component : _componentsToChange) {
component.first->par(this->_parToChange.c_str()).parse(component.second.c_str());
}
}
} // namespace SDN4CoRE
| 3,560
|
C++
|
.cc
| 85
| 36.470588
| 107
| 0.680335
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,211
|
DynamicModuleHandling.cc
|
CoRE-RG_SDN4CoRE/src/sdn4core/utility/dynamicmodules/DynamicModuleHandling.cc
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include <sdn4core/utility/dynamicmodules/DynamicModuleHandling.h>
#include <string>
using namespace std;
namespace SDN4CoRE {
cRuntimeError createErrorMessage(const char* name, const char* nedModulePath, const char* reason) {
string msg = "Cannot create dynamic module \"";
msg += name;
msg += "\" of type \"";
msg += nedModulePath;
msg += ": ";
msg += reason;
return cRuntimeError("%s",msg.c_str());
}
cModule* createFinalizeAndScheduleDynamicModule(const char* nedModulePath,
const char* name, cModule* parentModule, bool isVector, SimTime at){
cModule* module = createDynamicModule(nedModulePath, name, parentModule, isVector);
if(module){
finalizeModuleAndSchedule(module,at);
} else {
throw createErrorMessage(name, nedModulePath, "Module creation failed.");
}
return module;
}
void finalizeModuleAndSchedule(cModule* module, SimTime at) {
// 3. Set up its parameters and gate sizes as needed;
module->finalizeParameters();
// 4. Tell the (possibly compound) module to recursively create its internal submodules and connections;
module->buildInside();
module->callInitialize();
// 5. Schedule activation message(s) for the new simple module(s).
module->scheduleStart(at);
}
cModule* createDynamicModule(const char* nedModulePath,
const char* name, cModule* parentModule, bool isVector) {
// 0. check parameters
if(!nedModulePath || !name || !parentModule)
{
throw cRuntimeError("Cannot create dynamic module: Missing Parameters.");
}
// 1. Find the factory object;
cModuleType * moduleType = cModuleType::get(nedModulePath);
if(!moduleType)
{
throw createErrorMessage(name, nedModulePath, "Can't find module type at given path.");
}
// check whether the module exists already
bool existsAsVector = parentModule->hasSubmoduleVector(name);
bool existsAsModule = parentModule->hasSubmodule(name);
if (existsAsModule && isVector)
{
throw createErrorMessage(name, nedModulePath, "Should be vector but already exists as non vector type.");
}
else if (existsAsModule && !isVector)
{
throw createErrorMessage(name, nedModulePath, "SubModule already exists in ParentModule.");
}
else if(existsAsVector && !isVector)
{
throw createErrorMessage(name, nedModulePath, "Should be non vector but already exists as vector type.");
}
// 2. Create the module;
cModule* module = nullptr;
if(isVector){
if(existsAsVector)
{
int size = getDynamicModuleVectorSize(name, parentModule);
parentModule->setSubmoduleVectorSize(name, size + 1);
module = moduleType->create(name, parentModule, size);
}
else
{
parentModule->addSubmoduleVector(name,1);
module = moduleType->create(name, parentModule, 0);
}
}
else
{
module = moduleType->create(name, parentModule);
}
return module;
}
int getDynamicModuleVectorSize(const char* name,
cModule* parentModule) {
// no longer required as this is checked beforehand
// if(parentModule->getSubmodule(name)){
// return -1;
// }
int size = 0;
for (; parentModule->getSubmodule(name,size); size++){};
return size;
}
} /* namespace SDN4CoRE */
| 4,096
|
C++
|
.cc
| 108
| 33.12037
| 113
| 0.698768
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,212
|
DeviceTable.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/devices/DeviceTable.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_DEVICEMANAGER_H_
#define __SDN4CORE_DEVICEMANAGER_H_
#include <omnetpp.h>
#include <sdn4core/controllerState/base/ControllerStateManagementBase.h>
//openflow
#include "openflow/openflow/controller/Switch_Info.h"
using namespace omnetpp;
namespace SDN4CoRE {
typedef std::pair<SwitchPort, SwitchPort> DeviceLink_t;
/**
* DeviceTable stores and manages devices and links for a controller application.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class DeviceTable: public ControllerStateManagementBase<cModule> {
public:
/**
* Adds a network device (switch) to the controller state and creates state modules.
* @param sw_info the switch to be added
* @return True if refreshed. False if its new.
*/
virtual bool addNetworkDevice(openflow::Switch_Info* sw_info);
/**
* Get the number of known switches.
* @note Is const because used in refreshDisplay() const
* @return The number of devices.
*/
virtual int getDeviceCount() const;
/**
* Get the number of known devices links.
* @note Is const because used in refreshDisplay() const
* @return The number of links.
*/
virtual int getLinkCount() const;
/**
* Adds a direct link between two network devices (e.g., discovered with LLDP).
* @param swMacFirst the first switch mac address
* @param portFirst the port of the first switch
* @param swMacSecond the second switch mac address
* @param portSecond the port of the second switch
* @return True if refreshed. False if its new.
*/
virtual bool linkNetworkDevices(std::string& swMacFirst, int portFirst,
std::string& swMacSecond, int portSecond);
/**
* Checks whether a given switch port is linked to another network
* device or is an host access port.
* @param swMac the switch mac address
* @param port the port of the switch
* @return True if linked to another network device.
*/
virtual bool isLinkedToNetworkDevice(std::string& swMac, int port);
/**
* Get the next switch port linked to a given switch port.
* @param swMac The switch
* @param port The port at the switch
* @return The linked switch port.
*/
virtual SwitchPort getLinkedSwitchPort(std::string& swMac, int port);
/**
* Collects all known ports of the switch that are linked to other network devices.
* @param swMac the switch mac address
* @return A vector containing all ports linked to other network devices.
* The .first element of a device link is always a port at the given switch.
*/
virtual std::vector<DeviceLink_t> getDeviceLinksForSwitch(std::string& swMac);
virtual bool loadConfig(cXMLElement* configuration) override;
virtual bool loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) override;
virtual void dumpConfigToStream(std::ostream& stream, int indentTabs = 0)
override;
protected:
/**
* Collects all known direct links between devices and erases bidirectional duplicates.
* @return The device links
*/
virtual std::vector<DeviceLink_t> getAllDeviceLinks();
virtual void initialize() override;
/**
* Updates the displaystring for links and switches
*/
virtual void refreshDisplay() const override;
protected:
/**
* Device Links known to this device table.
* Stores all links for both directions, so be aware of the duplicates!
*/
std::map<SwitchPort, SwitchPort> links;
};
} /*end namespace SDN4CoRE*/
#endif
| 4,317
|
C++
|
.h
| 107
| 35.831776
| 91
| 0.716094
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,213
|
SRPTableManagement.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/srp/SRPTableManagement.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef OPENFLOW_REALTIME_CONTROLLERAPPS_SRPTABLEMANAGEMENT_H_
#define OPENFLOW_REALTIME_CONTROLLERAPPS_SRPTABLEMANAGEMENT_H_
#include <omnetpp.h>
#include <sdn4core/controllerState/base/ControllerStateManagementBase.h>
//STD
#include <vector>
//inet
#include "inet/linklayer/common/MACAddress.h"
//CoRE4INET
#include "core4inet/services/avb/SRP/SRPTable.h"
//AUTO_GENERATED MESSAGES
#include "core4inet/linklayer/ethernet/avb/SRPFrame_m.h"
//openflow
#include "openflow/openflow/controller/Switch_Info.h"
//SDN4CoRe
namespace SDN4CoRE {
// TODO register listeners for SRP events such as aging, etc.
/**
* SRPTableManagement manages the SRPTable operations for the controller.
* It holds one SRP table per switch.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class SRPTableManagement: public ControllerStateManagementBase<
CoRE4INET::SRPTable> {
public:
/**
* Information how to forward AVB messages.
*/
class SRPForwardingInfo_t {
public:
int inPort;
inet::MACAddress dest;
uint16_t vlanID;
uint8_t pcp;
uint8_t srClass;
uint64_t streamID;
std::vector<int> outports;
};
/**
* Register a talker for a switch and inport.
* @param swinfo The switch recieving the talker advertise.
* @param arrivalPort The ingress port at the receiving switch.
* @param talkerAdvertise The original talker advertise message recieved in the switch.
* @return true if the talker table has been updated.
*/
virtual bool registerTalker(openflow::Switch_Info* swinfo, int arrivalPort,
CoRE4INET::TalkerAdvertise* talkerAdvertise);
/**
* Register a listener for a switch and inport.
* @param swinfo The switch recieving the listener ready.
* @param arrivalPort The ingress port at the receiving switch.
* @param listenerReady The original listener ready message recieved in the switch.
* @return true if the listener table has been updated.
*/
virtual bool registerListener(openflow::Switch_Info* swinfo,
int arrivalPort, CoRE4INET::ListenerReady* listenerReady);
/**
* Get the out port for a certain talker at a switch.
* @param switchInfo The switch to find the outport for.
* @param streamId The stream ID of the talker.
* @param vid The vlan id of the talker.
* @return The outport for the talker.
*/
virtual int getTalkerPort(openflow::Switch_Info* switchInfo, uint64_t streamId, uint16_t vid);
/**
* Provides a forwarding information for AVBFrames according to the SRPTable of a
* switch and a stream.
* @param swinfo The switch handling the frame
* @param streamID The stream to be forwarded.
* @param vlan_id The VLAN ID of the frame
* @return SRPForwardingInfo_t containing all information to create a match.
*/
virtual SRPForwardingInfo_t* getForwardingInfoForStreamID(
openflow::Switch_Info* swinfo, uint64_t streamID, uint16_t vlan_id);
virtual bool loadConfig(cXMLElement* configuration) override;
virtual bool loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) override;
virtual void dumpConfigToStream(std::ostream& stream, int indentTabs = 0)
override;
protected:
/**
* override method from ControllerStateManagementBase to react to srpTable creation
*/
virtual void onCreateManagedState(CoRE4INET::SRPTable* managedState,
std::string& swMacAddr) override;
private:
/** Helper function to locate the srpManager tag in the XML configuration.
*
* @param configuration the xml configuration
* @return the srpManager xml element if found, else nullptr
*/
cXMLElement* locateSrpManagerInXML(cXMLElement* configuration);
/**
* Helper function to parse the xml of one srp table.
* This is needed as the SRPTable class importFromXML function requires
* valid ports which have not yet been created from the manager.
* @param srp the SRPTable xml to read
* @param swMac the switch mac the table belongs to
* @return true if the table has been updated, else false
*/
bool readSRPTableFromXML(cXMLElement* srp, const std::string& swMac);
/**
* Helper function to export one srp table to xml.
* This is needed as the SRPTable class exportToXML function uses
* the port modules dynamically created. @see~readSRPTableFromXML()
* @param table the SRP table to export
* @param indentTabs optional additional indentation for each line.
* @return the created XML string
*/
std::string exportSRPTableToXML(CoRE4INET::SRPTable* table, const std::string& swMac, int indentTabs=0);
};
} /*end namespace SDN4CoRE*/
#endif /* OPENFLOW_REALTIME_CONTROLLERAPPS_SRPTABLEMANAGEMENT_H_ */
| 5,693
|
C++
|
.h
| 130
| 39
| 108
| 0.712146
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,214
|
TopologyManagement.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/topology/TopologyManagement.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_TOPOLOGYMANAGEMENT_H_
#define __SDN4CORE_TOPOLOGYMANAGEMENT_H_
#include <omnetpp.h>
#include <sdn4core/controllerState/base/ControllerStateManagementBase.h>
#include <sdn4core/controllerState/hosts/HostTable.h>
#include <sdn4core/controllerState/devices/DeviceTable.h>
// std
#include <list>
// INET
#include "inet/linklayer/common/MACAddress.h"
#include "inet/networklayer/common/L3Address.h"
// openflow
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/controller/Switch_Info.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* The Topology Management uses the @see~HostTable and @see~DeviceTable to discover hosts and routes.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class TopologyManagement: public ControllerStateManagementBase<cModule> {
public:
TopologyManagement();
~TopologyManagement();
typedef std::list<SwitchPort> Route;
/**
* Find the outport for a packet_in and a switch info
* @param swInfo Info about the switch
* @param packetIn The incoming packet to route
* @return The output port number if found, else -1
*/
virtual int findOutportAtSwitch(openflow::Switch_Info * swInfo,
openflow::OFP_Packet_In* packetIn);
/**
* Find the outport for a host MAC address at a certain switch.
* @param switchId The switch id (device MAC address)
* @param hostMac The MAC address of the host
* @return The output port number if found, else -1
*/
virtual int findOutportAtSwitch(std::string switchId,
inet::MACAddress hostMac);
/**
* Find the outport for a host IP address at a certain switch.
* @param switchId The switch id (device MAC address)
* @param hostIp The IP address of the host
* @return The output port number if found, else -1
*/
virtual int findOutportAtSwitch(std::string switchId,
inet::L3Address hostIp);
/**
* Find the outport for a host at a certain switch.
* @param switchId The switch id (device MAC address)
* @param host The HostEntry from the HostTable
* @return The output port number if found, else -1
*/
virtual int findOutportAtSwitch(std::string switchId,
HostTable::HostEntry* host);
/**
* Find out the edge device and port to which the host MAC is connected.
* @param hostMac The MAC address of the host
* @return The switchId and port pair connected to the host if found, else nullptr
*/
virtual SwitchPort findEdgePort(inet::MACAddress hostMac);
/**
* Find out the edge device and port to which the host IP is connected.
* @param hostIp The IP address of the host
* @return The switchId and port pair connected to the host if found, else nullptr
*/
virtual SwitchPort findEdgePort(inet::L3Address hostIp);
/**
* Find out the edge device and port to which the host IP is connected.
* @param host The HostEntry from the HostTable
* @return The switchId and port pair connected to the host if found, else nullptr
*/
virtual SwitchPort findEdgePort(HostTable::HostEntry* host);
/**
* Find a route through the topology to a host MAC starting at a switch.
* @param fromSwitch The switch id (device MAC address) of the starting point
* @param hostMac The MAC address of the host
* @return An ordered list representing the path through the network,
* empty list if no route was found
*/
virtual Route findRoute(std::string fromSwitch,
inet::MACAddress hostMac);
/**
* Find a route through the topology to a host IP starting at a switch.
* @param fromSwitch The switch id (device MAC address) of the starting point
* @param hostIp The IP address of the host
* @return An ordered list representing the path through the network,
* empty list if no route was found
*/
virtual Route findRoute(std::string fromSwitch,
inet::L3Address hostIp);
/**
* Find a route through the topology to a host starting at a switch.
* @param fromSwitch The switch id (device MAC address) of the starting point
* @param host The HostEntry from the HostTable
* @return An ordered list representing the path through the network,
* empty list if no route was found
*/
virtual Route findRoute(std::string fromSwitch,
HostTable::HostEntry* host);
protected:
/**
* Calculate a route recursively from the switch to the host.
* @param fromSwitch The switch to start from
* @param host The host to get to
* @return An ordered list representing the path through the network,
* empty list if no route was found
*/
virtual Route calculateRoute(std::string fromSwitch,
HostTable::HostEntry* host, std::string previousSwitch = "");
/**
* Looks up the host and switchId combination in the cache and returns the outport.
* @param switchId the switch id to look for
* @param host the host to look for
* @return The outport if found, else -1
*/
virtual int findNextHopInCache(std::string switchId,
HostTable::HostEntry* host);
/**
* Removes an entry from the next hop cache.
* @param switchId the switch of the entry
* @param host the host of the entry
*/
virtual void cacheInvalidateNextHop(std::string switchId,
HostTable::HostEntry* host);
/**
* Add an entry to the next hop cache.
* @param switchId the switch of the entry
* @param host the host of the entry
* @param port the port of the entry
*/
virtual void cacheNextHop(std::string switchId,
HostTable::HostEntry* host, int port);
virtual void initialize() override;
protected:
/**
* Access to the host table module.
*/
HostTable* hostTable;
/**
* Access to the device table module.
*/
DeviceTable* deviceTable;
/**
* Cached hops for host entries using MACAddresses.
*/
std::map<inet::MACAddress, std::map<std::string, int>> cachedHops;
};
} /*end namespace SDN4CoRE*/
#endif
| 6,891
|
C++
|
.h
| 169
| 35.633136
| 101
| 0.69879
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,215
|
PortModule.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/base/PortModule.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_PORTMODULE_H_
#define __SDN4CORE_PORTMODULE_H_
#include <omnetpp.h>
using namespace omnetpp;
namespace SDN4CoRE{
class PortModule : public cSimpleModule{
public:
int getPort();
void setPort(int port);
protected:
virtual void initialize()override;
private:
int _port;
};
}
#endif
| 997
|
C++
|
.h
| 30
| 31.3
| 78
| 0.764092
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,216
|
ControllerStateManagementBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/base/ControllerStateManagementBase.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_CONTROLLERSTATEMANAGEMENTBASE_H_
#define __SDN4CORE_CONTROLLERSTATEMANAGEMENTBASE_H_
#include <omnetpp.h>
#include <map>
#include <string>
#include <utility>
#include <algorithm>
#include <fstream>
#include <iostream>
#include "inet/common/InitStages.h"
#include <sdn4core/controllerState/base/PortModule.h>
#include <sdn4core/utility/dynamicmodules/DynamicModuleHandling.h>
using namespace omnetpp;
namespace SDN4CoRE {
#define MODULE_SPACING 70
/**
* Structure representing a switch port for the controller state and topology.
*
* @author Timo Haeckel, for HAW Hamburg
*/
struct SwitchPort {
std::string switchId;
int port;
SwitchPort() : switchId(""), port(-1) {}
SwitchPort(std::string switchId, int port) : switchId(switchId), port(port) {}
bool empty() { return switchId.empty(); }
bool operator<(const SwitchPort& other) const {
if(this->switchId == other.switchId) {
return this->port < other.port;
}
return this->switchId < other.switchId;
}
bool operator>(const SwitchPort& other) const {
return other < *this;
}
bool operator==(const SwitchPort& other) const {
return this->switchId == other.switchId && this->port == other.port;
}
bool operator!=(const SwitchPort& other) const {
return !operator==(other);
}
friend std::ostream & operator << (std::ostream &out, const SwitchPort &switchPort) {
out << "{switchId=\"" << switchPort.switchId << "\", port=\"" << switchPort.port << "\"}";
return out;
}
};
/**
* Workaround to count module creations for the template class.
* Used to set display options.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class ControllerStateManagementWithID: public cSimpleModule {
public:
ControllerStateManagementWithID() :
managerID(nextID++) {
WATCH(managerID);
}
const int getMangerID() {
return managerID;
}
private:
static int nextID;
const int managerID;
};
/**
* SimpleModule to manage controller state @see~ControllerState
*
* TODO is it possible that cached switches etc. are removed at
* runtime and thus the cache should be verified?
*
* @author Timo Haeckel, for HAW Hamburg
*/
template<class ManagedType = cModule>
class ControllerStateManagementBase: public ControllerStateManagementWithID {
public:
/**
* Read a configuration from the XML and load it into the controller state.
* @param configuration the XML configuration to read.
* @return true if the controller state has changed.
*/
virtual bool loadConfig(cXMLElement* configuration) {
return false;
}
/**
* Read a configuration for one specific switch from the XML and load it
* into the controller state.
* @param configuration the XML configuration to read.
* @return true if the controller state has changed.
*/
virtual bool loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) {
return false;
}
/**
* Interface function to dump XML config to file if specified in the parameter "dumpConfig".
* Calls dumpConfigToStream() to get the state as XML from the implementing class.
*/
virtual void dumpConfig() {
std::string filename = par("dumpConfig").stdstringValue();
if (!filename.empty()) {
std::ofstream file;
file.open(filename.c_str(), std::ios::app);
if (!file.is_open())
throw cRuntimeError("Cannot open output file");
dumpConfigToStream(file);
file.close();
}
}
/**
* Dumps the managed state as formatted XML into the given output stream provided by the user.
* @param stream the output stream to write to (can be, e.g., a filestream or stringstream)
* @param indentTabs number of tabs to use for base indentation at beginning of each line.
*/
virtual void dumpConfigToStream(std::ostream& stream, int indentTabs = 0) {
std::string indent = std::string(indentTabs, '\t');
stream << indent << "<!--not implemented for this manager-->"
<< std::endl;
}
protected:
//used as a workaround for dynamically created modules during initialization from config
virtual int numInitStages() const override {
return inet::NUM_INIT_STAGES;
}
virtual void initialize() override {}
virtual void initialize(int stage) override {
if (stage == 0) {
initialize();
} else if (stage == inet::INITSTAGE_LAST) {
loadConfig(par("config"));
}
}
virtual void finish() override {
dumpConfig();
}
/**
* Get the switch state compound module for the switch.
*
* @param swMacAddr The info of the switch to look for.
* @return The switch state compound module, nullptr if not found.
*/
cModule* getSwitch(std::string swMacAddr) {
if (cachedSwitches.find(swMacAddr) != cachedSwitches.end()) {
return cachedSwitches[swMacAddr];
}
return findSwitchState(swMacAddr);
}
/**
* Locates all known switches and returns them.
*
* @return a map of all switches with there switch mac address as the key.
*/
const std::map<std::string, cModule*>& getAllSwitches() {
refreshCachedSwitches();
return cachedSwitches;
}
/**
* Create a switch the compound module.
*
* @note This will throw an error if the module already exists.
* Maybe use getOrCreateSwitch() instead.
*
* @param swMacAddr The info of the switch to look for.
* @return the compound module that was created/found.
*/
cModule* createSwitch(std::string swMacAddr) {
cModule* switchModule = createFinalizeAndScheduleDynamicModule(
"sdn4core.controllerState.base.ControllerSwitchState",
"switchState", this->getParentModule(), true);
if (!switchModule) {
throw cRuntimeError(
"Could not create state module for switch %s ",
swMacAddr.c_str());
}
onCreateSwitch(switchModule, swMacAddr);
return switchModule;
}
/**
* Checks whether a given switch is already present else create
* the compound module.
*
* @param swMacAddr The info of the switch to look for.
* @return the compound module that was created/found.
*/
cModule* getOrCreateSwitch(std::string swMacAddr) {
cModule* switchModule = getSwitch(swMacAddr);
if (!switchModule) {
switchModule = createSwitch(swMacAddr);
}
return switchModule;
}
/**
* Function to be executed when a new switch module was successfully created.
* @param switchModule The newly created switchModule
* @param swMacAddr Info about the created switch.
*/
void onCreateSwitch(cModule* switchModule, std::string swMacAddr) {
switchModule->par("switchName").setStringValue(swMacAddr);
setModuleDisplayName(switchModule, swMacAddr);
cachedSwitches[swMacAddr] = switchModule;
}
/**
* Get the port module of a switch.
*
* @param swMacAddr The info of the switch to look for.
* @param port The port id to look for.
* @return The switch port module, nullptr if not found.
*/
PortModule* getSwitchPort(std::string swMacAddr, int port, cModule* switchModule = nullptr) {
SwitchPort switchPortPair(swMacAddr, port);
if (cachedSwitchPorts.find(switchPortPair) != cachedSwitchPorts.end()) {
return cachedSwitchPorts[switchPortPair];
}
return findSwitchPort(swMacAddr, port);
}
/**
* Locates all switch port objects an returns them.
*
* @return a map of all switch ports with there switch mac address and port as the key.
*/
const std::map<SwitchPort, PortModule*>& getAllSwitchPorts() {
refreshCachedPorts();
return cachedSwitchPorts;
}
/**
* Create a port module inside a switch compound module.
*
* @note This will throw an error if the module already exists.
* Maybe use getOrCreateSwitchPort() instead.
*
* @param swMacAddr The info of the switch to look for.
* @param port The port id to look for.
* @return the compound module that was created/found.
*/
PortModule* createSwitchPort(std::string swMacAddr, int port, cModule* switchModule = nullptr) {
if(!switchModule) {
switchModule = getOrCreateSwitch(swMacAddr);
}
PortModule* portModule =
dynamic_cast<PortModule*>(createFinalizeAndScheduleDynamicModule(
"sdn4core.controllerState.base.PortModule",
"portModules", switchModule, true));
if (!portModule) {
throw cRuntimeError(
"Could not create port module %s for switch %s ",
std::to_string(port).c_str(), swMacAddr.c_str());
}
onCreateSwitchPort(portModule, swMacAddr, port);
return portModule;
}
/**
* Checks whether a portmodule for the given switch port is already present
* if not the module will be dynamically created.
*
* @param swMacAddr The info of the switch to look for.
* @param port The port id to look for.
* @return the compound module that was created/found.
*/
PortModule* getOrCreateSwitchPort(std::string swMacAddr, int port, cModule* switchModule = nullptr) {
PortModule* portModule = getSwitchPort(swMacAddr, port, switchModule);
if (!portModule) {
portModule = createSwitchPort(swMacAddr, port);
}
return portModule;
}
/**
* Function to be executed when a new port module was successfully created.
* @param portModule The newly created portModule
* @param swMacAddr Info about the created switch.
* @param port The created port id.
*/
virtual void onCreateSwitchPort(PortModule* portModule,
std::string swMacAddr, int port) {
setModulePosition(portModule, MODULE_SPACING * (port + 1),
MODULE_SPACING);
setModuleDisplayName(portModule, "Port " + std::to_string(port));
portModule->setPort(port);
cachedSwitchPorts[SwitchPort(swMacAddr, port)] = portModule;
}
/**
* Get the managed state module for the switch.
*
* @param swMacAddr The info of the switch to look for.
* @return the managed state module, nullptr if not found.
*/
ManagedType* getManagedState(std::string swMacAddr) {
if (cachedManagedStates.find(swMacAddr) != cachedManagedStates.end()) {
return cachedManagedStates[swMacAddr];
}
return findManagedPerSwitchState(swMacAddr);
}
/**
* Locates all managed state objects an returns them.
*
* @return a map of all managed objects with there switch mac address as the key.
*/
const std::map<std::string, ManagedType*>& getAllManagedStates() {
refreshCachedManagedStates();
return cachedManagedStates;
}
/**
* Checks whether the state module already exists for a
* given switch if not the module will be dynamically created.
*
* @param swMacAddr The info of the switch to look for.
* @return the managed state module that was created/found.
*/
ManagedType* getOrCreateManagedState(std::string swMacAddr) {
ManagedType* managedState = getManagedState(swMacAddr);
if (!managedState) {
managedState = dynamic_cast<ManagedType*>(getOrCreatePerSwitchState(
swMacAddr, par("switchStateModulePath").stringValue(),
par("switchStateModuleName").stringValue(), false));
if (!managedState) {
throw cRuntimeError(
"Could not create managed switch state module for switch %s ",
swMacAddr.c_str());
}
onCreateManagedState(managedState, swMacAddr);
}
return managedState;
}
/**
* Function to be executed when a new managed state module was successfully created.
* @param managedState The newly created managed state
* @param swMacAddr Info about the created switch.
*/
virtual void onCreateManagedState(ManagedType* managedState,
std::string& swMacAddr) {
setModulePosition(managedState, MODULE_SPACING,
MODULE_SPACING * (this->getMangerID() + 2));
cachedManagedStates[swMacAddr] = managedState;
}
/**
* Get a specific state module for the switch.
*
* @param swMacAddr The info of the switch to look for.
* @param stateName The name of the switch state to look for.
* @return the state module, nullptr if not found
*/
cModule* getPerSwitchState(std::string& swMacAddr, const char* stateName) {
return findPerSwitchState(swMacAddr, stateName);
}
/**
* Checks whether the managed state module already exists for a
* given switch if not the module will be dynamically created.
*
* @param swMacAddr The info of the switch to look for.
* @param stateModulePath ned module path to create a new module.
* @param stateName The name of the switch state to look for.
* @return the state module that was found/created.
*/
cModule* getOrCreatePerSwitchState(std::string& swMacAddr,
const char* stateModulePath, const char* stateName, bool isVector) {
cModule* state = getPerSwitchState(swMacAddr, stateName);
if (!state) {
if (cModule* switchModule = getOrCreateSwitch(swMacAddr)) {
if (!(state = createFinalizeAndScheduleDynamicModule(
stateModulePath, stateName, switchModule, isVector))) {
throw cRuntimeError(
"Could not create state module %s for switch %s ",
stateName, swMacAddr.c_str());
}
onCreatePerSwitchState(state, swMacAddr);
}
}
return state;
}
/**
* Function to be executed when a new managed state module was successfully created.
* @param portModule The newly created portModule
* @param swMacAddr Info about the created switch.
*/
virtual void onCreatePerSwitchState(cModule* state,
std::string& swMacAddr) {
}
private:
/**
* Finds switch state compound module containing all switch state modules in
* the ned module hierarchy.
*
* @param swMacAddr The info of the switch to look for.
* @return the switch state compound module if found, else nullptr.
*/
cModule* findSwitchState(std::string& swMacAddr) {
refreshCachedSwitches();
auto found = cachedSwitches.find(swMacAddr);
if (found != cachedSwitches.end()) {
return found->second;
}
return nullptr;
}
/**
* Locates all switches and adds them to the cache.
*/
void refreshCachedSwitches() {
cachedSwitches.clear();
int numSwitches = getDynamicModuleVectorSize("switchState",
this->getParentModule());
for (int i = 0; i < numSwitches; i++) {
cModule* currentModule = this->getParentModule()->getSubmodule(
"switchState", i);
std::string mac = currentModule->par("switchName").stdstringValue();
cachedSwitches[mac] = currentModule;
}
}
/**
* Finds the port module for the given switch in the ned module hierarchy.
*
* @param swMacAddr The info of the switch to look for.
* @return the switch port module if found, else nullptr.
*/
PortModule* findSwitchPort(std::string& swMacAddr, int port) {
refreshCachedPorts();
auto found = cachedSwitchPorts.find(SwitchPort(swMacAddr, port));
if (found != cachedSwitchPorts.end()) {
return found->second;
}
return nullptr;
}
/**
* Locates all switch ports and adds them to the cache.
*/
void refreshCachedPorts() {
refreshCachedSwitches();
cachedSwitchPorts.clear();
for (auto sw : cachedSwitches) {
int numPorts = getDynamicModuleVectorSize("portModules", sw.second);
for (int i = 0; i < numPorts; i++) {
PortModule* currentPort =
dynamic_cast<PortModule*>(sw.second->getSubmodule(
"portModules", i));
int port = currentPort->getPort();
cachedSwitchPorts[SwitchPort(sw.first, port)] = currentPort;
}
}
}
/**
* Finds the managed switch state for the given switch in the ned module
* hierarchy.
*
* @param swMacAddr The info of the switch to look for.
* @return the managed state module if found, else nullptr.
*/
ManagedType* findManagedPerSwitchState(std::string& swMacAddr) {
auto found = cachedManagedStates.find(swMacAddr);
if (found != cachedManagedStates.end()) {
return found->second;
}
return nullptr;
}
/**
* Locates all managed modules for switches and adds them to the cache.
*/
void refreshCachedManagedStates() {
refreshCachedSwitches();
cachedManagedStates.clear();
for (auto sw : cachedSwitches) {
ManagedType* managedState =
dynamic_cast<ManagedType*>(sw.second->getSubmodule(
par("switchStateModuleName").stringValue(), 0));
if (managedState) {
cachedManagedStates[sw.first] = managedState;
}
}
}
/**
* Finds a certain switch state for the given switch in the ned module
* hierarchy.
*
* @param swMacAddr The info of the switch to look for.
* @paran stateName The name of the switch state to look for.
* @return the state module if found, else nullptr.
*/
cModule* findPerSwitchState(std::string& swMacAddr, const char* stateName,
int index = -1) {
if (cModule* switchState = getSwitch(swMacAddr)) {
return switchState->getSubmodule(stateName, index);
}
return nullptr;
}
void setModuleDisplayName(cModule* module, std::string name) {
std::string newDisplayString = "t=" + name;
module->getDisplayString().updateWith(newDisplayString.c_str());
}
void setModulePosition(cModule* module, int x, int y) {
std::string newDisplayString = "p=" + std::to_string(x) + ","
+ std::to_string(y);
module->getDisplayString().updateWith(newDisplayString.c_str());
}
protected:
/**
* Known switch state compound modules that are cached on creation
* and dynamic lookups.
*
* map key is the switches MAC Address as a string from the swMacAddr.
* map value is the cached cModule reference of the switch state compound
* module.
*
* @note A switch module might exist that is unknown to this instance
* of ControllerStateManagementBase! In some edge, cases modules that are
* cached might not be valid anymore.
*/
std::map<std::string, cModule*> cachedSwitches;
/**
* Known switch port modules that are cached on creation and dynamic lookups.
*
* map key is the pair of a switches MAC Address as a string from the swMacAddr
* and the port index.
* map value is the cached cModule reference of the switch PortModule.
*
* @note A switch module might exist that is unknown to this instance
* of ControllerStateManagementBase! In some edge cases, modules that are
* cached might not be valid anymore.
*/
std::map<SwitchPort, PortModule*> cachedSwitchPorts;
/**
* Known managed switch state modules that are cached on creation and
* dynamic lookups.
*
* map key is the switches MAC Address as a string from the swMacAddr.
* map value is the cached cModule reference of the switch state compound
* module.
*
* @note A switch module might exist that is unknown to this instance
* of ControllerStateManagementBase! In some edge cases, modules that are
* cached might not be valid anymore.
*/
std::map<std::string, ManagedType*> cachedManagedStates;
};
} // End namespace SDN4CoRE
#endif
| 21,387
|
C++
|
.h
| 548
| 31.622263
| 105
| 0.651095
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,217
|
MACTableManagement.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/mac/MACTableManagement.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef OPENFLOW_REALTIME_CONTROLLERAPPS_MACTABLEMANAGEMENT_H_
#define OPENFLOW_REALTIME_CONTROLLERAPPS_MACTABLEMANAGEMENT_H_
#include <omnetpp.h>
#include <sdn4core/controllerState/base/ControllerStateManagementBase.h>
//STD
#include <vector>
//INET
#include "inet/linklayer/common/MACAddress.h"
#include "inet/linklayer/ethernet/switch/MACAddressTable.h"
//openflow
#include "openflow/openflow/controller/Switch_Info.h"
namespace SDN4CoRE {
#define MAC_MANAGER_OUTPORT_FLOOD -1
class MACTableManagement;
/**
* Extended MACAddressTable for controller state which has friend class MACTableManagement
*/
class FriendMACAddressTable: public inet::MACAddressTable {
friend class MACTableManagement;
};
/**
* MACTableManagement manages the MAC tables for a controller application.
* It holds one MACTabel per switch.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class MACTableManagement: public ControllerStateManagementBase<
FriendMACAddressTable> {
public:
/**
* Updates the MAC table according to the Header Fields provided.
* @param sw_info the switch to update
* @param source the source to update
* @param in_port the in port to update
* @return True if refreshed. False if it is new.
*/
virtual bool update(openflow::Switch_Info* sw_info, inet::MACAddress source,
uint32_t in_port, int vlan_id = 0);
/**
* Lookup the output port a destination mac address at a switch.
* @param sw_info the switch to lookup
* @param destination the destination to lookup
* @return return the port to output the packet to.
* return -1 if there is no entry in the table.
*/
virtual int lookup(openflow::Switch_Info* sw_info,
inet::MACAddress destination, int vlan_id = 0);
virtual bool loadConfig(cXMLElement* configuration) override;
virtual bool loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) override;
virtual void dumpConfigToStream(std::ostream& stream, int indentTabs = 0)
override;
protected:
/**
* override method from ControllerStateManagementBase to react to srpTable creation
*/
virtual void onCreateManagedState(FriendMACAddressTable* managedState,
std::string& swMacAddr) override;
};
} /*end namespace SDN4CoRE*/
#endif /* OPENFLOW_REALTIME_CONTROLLERAPPS_MACTABLEMANAGEMENT_H_ */
| 3,162
|
C++
|
.h
| 77
| 37.415584
| 90
| 0.735419
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,218
|
HostTable.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/controllerState/hosts/HostTable.h
|
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// c Timo Haeckel, for HAW Hamburg
//
#ifndef __SDN4CORE_HOSTTABLE_H_
#define __SDN4CORE_HOSTTABLE_H_
#include <omnetpp.h>
#include <sdn4core/controllerState/base/ControllerStateManagementBase.h>
// STD
#include <list>
#include <map>
// INET
#include "inet/linklayer/common/MACAddress.h"
#include "inet/networklayer/common/L3Address.h"
// openflow
#include "openflow/messages/OFP_Packet_In_m.h"
#include "openflow/openflow/controller/Switch_Info.h"
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Host Table that can learn and lookup network hosts for an SDN controller application.
* The table assumes the first detection point of the host mac as the entry point into the network.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class HostTable: public ControllerStateManagementBase<cModule> {
public:
/**
* Representation of a HostTable entry.
* Contains the known MAC and IP Addresses, VLAN IDs, switch and port.
*/
struct HostEntry {
std::string nodeName = "UNKNOWN"; //TODO add node name for visualization
inet::MACAddress macAddress;
std::string switch_id = "";
int portno = -1; // Input port
std::vector<unsigned int> vids; // VLAN ID
std::vector<inet::L3Address> ipAddresses;
bool learned = true; // true if learned during runtime, false if preconfigured
const simtime_t insertionTime; // time when entry was created
simtime_t lastUpdated; // for aging of unused entries
HostEntry() :
insertionTime(simTime()), lastUpdated(simTime()) {
}
};
friend std::ostream& operator<<(std::ostream& os, const HostEntry& entry);
struct MAC_compare {
bool operator()(const inet::MACAddress& u1, const inet::MACAddress& u2) const {
return u1.compareTo(u2) < 0;
}
};
typedef std::list<HostEntry*> HostList;
typedef std::map<inet::MACAddress, HostEntry*, MAC_compare> HostMapByMac;
typedef std::map<inet::L3Address, HostEntry*> HostMapByIp;
typedef std::map<std::string, HostList> HostMapBySwitch;
public:
HostTable();
~HostTable();
virtual bool loadConfig(cXMLElement* configuration) override;
virtual bool loadConfigForSwitch(const std::string& swMacAddr,
cXMLElement* configuration) override;
virtual void dumpConfigToStream(std::ostream& stream, int indentTabs = 0)
override;
/**
* Update HostTable using the source info inside the packet in message.
* @param packetIn The packet in information to learn.
* @param swInfo The source switch of the packet in.
* @return True if refreshed, false if a new entry was created.
*/
virtual bool update(openflow::OFP_Packet_In* packetIn, openflow::Switch_Info * swInfo);
/**
* Update HostTable using minimal source info as in MACAddressTables.
* @param sw_info the switch to update
* @param source the source to update
* @param in_port the in port to update
* @param vlan_id the vlan id to update
* @return True if refreshed, false if a new entry was created.
*/
virtual bool update(openflow::Switch_Info* swInfo, inet::MACAddress source,
uint32_t in_port, int vlan_id = 0);
/**
* Look up a host by by the given MAC address.
* @param address The address to look up
* @param doAging Check if the found entry is outdated
* @return A host entry matching the MAC address if found, else nullptr
*/
virtual HostEntry* getHostForMacAddress(const inet::MACAddress& address, bool doAging=true);
/**
* Look up a host by the given IP address.
* @param address The address to look up
* @param doAging Check if the found entry is outdated
* @return A host entry matching the IP address if found, else nullptr
*/
virtual HostEntry* getHostForIpAddress(const inet::L3Address& address, bool doAging=true);
/**
* Look up hosts connected to a switch.
* @param switch_id The switch id to look up
* @param doAging Check if the found entry is outdated
* @return A list of host entries connected to the host
*/
virtual HostList getHostsForSwitch(const std::string& switch_id, bool doAging=true);
/**
* Get the number of known hosts.
* @note Is const because used in refreshDisplay() const
* @return The number of hosts.
*/
virtual int getHostCount() const;
/**
* @brief Remove aged entries
*/
virtual void removeAgedEntries();
/*
* It calls removeAgedEntries() if and only if at least
* 1 second has passed since the method was last called.
*/
virtual void removeAgedEntriesIfNeeded();
/**
* For lifecycle: clears all entries from the vlanAddressTable.
*/
virtual void clearTable();
/**
* Set the agingTime of host entries.
* @param agingTime the aging time to set.
*/
virtual void setAgingTime(simtime_t agingTime);
/**
* Reset the agingTime to the one specified in the module parameter.
*/
virtual void resetDefaultAging();
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
/**
* Updates the displaystring for links and switches
*/
virtual void refreshDisplay() const override;
/**
* Add a host to the table updating an old entry or inserting the given pointer.
* @note The pointer now belongs and its lifecycle will be managed by the table.
* @param entry The entry to be added
* @return True if an existing entry was refreshed, false if pointer was added
*/
virtual bool addHost(HostEntry* entry);
/**
* Remove a host from the table.
* @note The pointer will be invalidated!
* @param entry The entry to be removed
* @return True if removed, false if not found
*/
virtual bool removeHost(HostEntry* entry);
/**
* Check if a host is aged based on the agingTime.
* @param entry The host entry
* @return True if the entry was last updated before aging time, else false
* False will also be returned for static hosts (learned=false)
*/
virtual bool isAgedHost(HostEntry* entry);
protected:
simtime_t agingTime; // Max idle time for address table entries
simtime_t lastPurge; // Time of the last call of removeAgedEntriesFromAllVlans()
HostMapByIp hostsByIp;
HostMapByMac hostsByMac;
HostMapBySwitch hostsBySwitch;
};
} /*end namespace SDN4CoRE*/
#endif
| 7,206
|
C++
|
.h
| 178
| 35.382022
| 99
| 0.699728
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,219
|
NetConfDefines.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/NetConfDefines.h
|
/*
* NetConfDefines.h
*
* Created on: 25.02.2021
* Author: micro
*/
#ifndef SDN4CORE_NETCONF_NETCONFDEFINES_H_
#define SDN4CORE_NETCONF_NETCONFDEFINES_H_
#define NETCONF_CONFIG_RUNNING "running"
#define NETCONF_CONFIG_CANDIDATE "candidate"
#endif /* SDN4CORE_NETCONF_NETCONFDEFINES_H_ */
| 304
|
C++
|
.h
| 11
| 25.727273
| 47
| 0.763889
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,220
|
NetConfConfigMultipart.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/multipart/NetConfConfigMultipart.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTRUCTURES_MULTIPART_NETCONFCONFIGMULTIPART_H_
#define SDN4CORE_NETCONF_DATASTRUCTURES_MULTIPART_NETCONFCONFIGMULTIPART_H_
//STD
#include <vector>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
namespace SDN4CoRE {
/**
* Multipart configuration data to be transferred in NetConf sessions
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfConfigMultipart: public NetConfConfig{
public:
NetConfConfigMultipart(){};
virtual ~NetConfConfigMultipart();
/**
* copy constructor to support copy of config data.
* @param old_obj the config to copy
*/
NetConfConfigMultipart (const NetConfConfigMultipart &old_obj);
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
virtual unsigned int getByteSize() override;
/**
* overrides message duplication to use class specific copy.
*/
virtual NetConfConfig_Base *dup() const override;
/**
* @returns a vector containing all stored NetConfConfigs
*/
std::vector<NetConfConfig*> getConfigurations();
/**
* set the a list of configuration for a NetConfConfigMultipart
* @param new_configs new list of configurations
*/
void setConfigurations(std::vector<NetConfConfig*> new_configs);
/**
* adds a single configurations to the list of stored configurations
* @param new_config
*/
void addConfiguration(NetConfConfig* new_config);
protected:
/**
* list of nested configurations
*/
std::vector<NetConfConfig*> _configs;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTRUCTURES_MULTIPART_NETCONFCONFIGMULTIPART_H_ */
| 2,446
|
C++
|
.h
| 68
| 32.397059
| 80
| 0.73867
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,221
|
NetConfConfigCommitTimestamp.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/transactionModel/NetConfConfigCommitTimestamp.h
|
//
// c Mohammad Fazel Soltani, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTRUCTURES_TRANSACTIONMODEL_NETCONFCONFIGCOMMITTIMESTAMP_H_
#define SDN4CORE_NETCONF_DATASTRUCTURES_TRANSACTIONMODEL_NETCONFCONFIGCOMMITTIMESTAMP_H_
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
namespace SDN4CoRE {
/**
* Commit time stamp data to be transferred in NetConf sessionsn.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfConfigCommitTimestamp: public NetConfConfig{
public:
typedef struct CommitTimestamp_t{
/**
* cycle as commit timestamp
*/
uint32_t cycle;
size_t period;
double time;
bool executeAtStartOfPeriod;
friend std::ostream& operator<<(std::ostream& os, const CommitTimestamp_t& obj){
os<<"{cycle="<<obj.cycle<<", period="<<obj.period<<", time="<<obj.time<<", executeAtStartOfPeriod="<<std::boolalpha<<obj.executeAtStartOfPeriod<<"}";
return os;
}
}CommitTimestamp_t;
public:
NetConfConfigCommitTimestamp();
virtual ~NetConfConfigCommitTimestamp();
/**
* copy constructor to support copy of config data.
* @param old_obj the config to copy
*/
NetConfConfigCommitTimestamp (const NetConfConfigCommitTimestamp &old_obj):NetConfConfig(old_obj) {
this->_timestamp = old_obj._timestamp;
};
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
virtual unsigned int getByteSize() override;
CommitTimestamp_t& getCommitTimestamp();
void setCommitTimestamp(CommitTimestamp_t& timestamp);
/**
* overrides message duplication to use class specific copy.
*/
virtual NetConfConfig_Base *dup() const override {return new NetConfConfigCommitTimestamp(*this);};
protected:
CommitTimestamp_t _timestamp;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTRUCTURES_TRANSACTIONMODEL_NETCONFCONFIGCOMMITTIMESTAMP_H_ */
| 2,692
|
C++
|
.h
| 67
| 35.895522
| 162
| 0.730578
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,222
|
NetConfConfigIEEE8021Qbv.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/ieee8021qbv/NetConfConfigIEEE8021Qbv.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTRUCTURES_IEEE8021QBV_NETCONFCONFIGIEEE8021QBV_H_
#define SDN4CORE_NETCONF_DATASTRUCTURES_IEEE8021QBV_NETCONFCONFIGIEEE8021QBV_H_
//STD
#include <string>
#include <vector>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
namespace SDN4CoRE {
/**
* IEEE8021Qbv configuration data to be transferred in NetConf sessions
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfConfigIEEE8021Qbv: public NetConfConfig {
public:
typedef struct IEEE8021QbvGateConfig {
/**
* The number of the port in the IEEE8021Q device
*/
int port;
/**
* Contains the GateControllist used in @see~IEEE8021QbvGateControlList
* GateStatus:
* C == close
* o == open
* EntryDuration: in seconds
* Format GateStatus,GateStatus,...,GateStatus:EntryDuration
* Example: "C,o,o,o,o,o,o,o:0.0001;o,C,o,o,o,o,o,o:0.0001"
*/
std::string gateControlList;
}IEEE8021QbvGateConfig_t;
public:
NetConfConfigIEEE8021Qbv();
virtual ~NetConfConfigIEEE8021Qbv();
/**
* copy constructor to support copy of config data.
* @param old_obj the config to copy
*/
NetConfConfigIEEE8021Qbv (const NetConfConfigIEEE8021Qbv &old_obj):NetConfConfig(old_obj) {
for(auto gateConfig: old_obj._gateConfigurations){
this->_gateConfigurations.push_back(new IEEE8021QbvGateConfig_t(*gateConfig));
}
};
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
virtual unsigned int getByteSize() override;
/**
* Finds the gate configuration for a specific port.
* @param port this port to look for
* @return the IEEE8021QbvGateConfig_t of the port if found, else null
*/
IEEE8021QbvGateConfig_t* getGateConfigurationForPort(int port);
/**
* Replaces the current config or inserts a new config for the port used in config
* @param config the config to insert
*/
void setGateConfiguration(IEEE8021QbvGateConfig_t* config);
const std::vector<IEEE8021QbvGateConfig_t*>& getGateConfigurations() const {
return _gateConfigurations;
}
void setGateConfigurations(
const std::vector<IEEE8021QbvGateConfig_t*>& gateConfigurations) {
_gateConfigurations = gateConfigurations;
}
/**
* overrides message duplication to use class specific copy.
*/
virtual NetConfConfig_Base *dup() const override {return new NetConfConfigIEEE8021Qbv(*this);};
protected:
std::vector<IEEE8021QbvGateConfig_t*> _gateConfigurations;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTRUCTURES_IEEE8021QBV_NETCONFCONFIGIEEE8021QBV_H_ */
| 3,524
|
C++
|
.h
| 91
| 33.835165
| 99
| 0.713407
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,223
|
OF_NetConfConfigFlowMod.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/openflow/OF_NetConfConfigFlowMod.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTRUCTURES_OPENFLOW_OF_NETCONFCONFIGOPENFLOW_H_
#define SDN4CORE_NETCONF_DATASTRUCTURES_OPENFLOW_OF_NETCONFCONFIGOPENFLOW_H_
//STD
#include <vector>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
//OpenFlow
#include "openflow/openflow/switch/flowtable/OF100_FlowTableEntry.h"
using namespace openflow;
namespace SDN4CoRE {
/**
* FlowMod configuration data to be transferred in NetConf sessions
*
* @author Tobias Haugg, for HAW Hamburg
*/
class OF_NetConfConfigFlowMod : public NetConfConfig {
public:
//OpenFlow commands
enum commands{
ADD_FLOW,
MODIFY_FLOW,
MODIFY_STRICT_FLOW,
DELETE_FLOW,
DELETE_STRICT_FLOW,
NO_ACTION
};
typedef struct OF_FlowTableConfig{
//OpenFlow Command
commands command;
//ID of the flowtable to be altert
uint8_t table_id;
//new flowtable entry
std::vector<OF100_FlowTableEntry*> flowTableEntries;
}OF_FlowTableConfig_t;
public:
OF_NetConfConfigFlowMod();
~OF_NetConfConfigFlowMod();
/**
* copy constructor to support copy of config data.
* @param old_obj the config to copy
*/
OF_NetConfConfigFlowMod(const OF_NetConfConfigFlowMod &old_obj);
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
unsigned int getByteSize()override;
/**
* overrides message duplication to use class specific copy.
*/
virtual NetConfConfig_Base *dup() const override;
/**
* adds a OF_FlowTableConfig_t to the flowTableConfigs (the list of flow tables that will be edited)
* @param flowTableConfig
*/
void addFlowTableConfig(OF_FlowTableConfig_t* flowTableConfig);
/**
* adds a OF_FlowTableConfig_t to the flowTableConfigs (the list of flow tables that will be edited)
* @param flowTableConfig
*/
void setFlowTableConfigs(std::vector<OF_FlowTableConfig_t*> flowTableConfigs);
/**
* return all flow flowTableConfigs
*/
std::vector<OF_FlowTableConfig_t*> getFlowTableConfigs();
protected:
/**
* open flow flowMod configuration
*/
std::vector<OF_FlowTableConfig_t*> flowTableConfigs;
};
}
#endif /* SDN4CORE_NETCONF_DATASTRUCTURES_OPENFLOW_OF_NETCONFCONFIGOPENFLOW_H_ */
| 3,066
|
C++
|
.h
| 89
| 30.247191
| 104
| 0.724848
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,224
|
NetConfConfigSRP.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/srp/NetConfConfigSRP.h
|
//
// c Tobias Haugg, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTRUCTURES_SRP_NETCONFCONFIGSRP_H_
#define SDN4CORE_NETCONF_DATASTRUCTURES_SRP_NETCONFCONFIGSRP_H_
//STD
#include <vector>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
//CoRE4INET
#include <core4inet/services/avb/SRP/SRPTable.h>
namespace SDN4CoRE {
/**
* SRP configuration data to be transferred in NetConf sessions
*
* @author Tobias Haugg, for HAW Hamburg
*/
class NetConfConfigSRP: public NetConfConfig{
public:
NetConfConfigSRP(){};
virtual ~NetConfConfigSRP(){};
/**
* copy constructor to support copy of config data.
* @param old_obj the config to copy
*/
NetConfConfigSRP (const NetConfConfigSRP &old_obj);
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
virtual unsigned int getByteSize() override;
/**
* overrides message duplication to use class specific copy.
*/
virtual NetConfConfig_Base *dup() const override;
/**
* set's the list of all TalkerEntries that should be configured
* @param talkers list of talkers
*/
void setTalkerEntries(std::vector<CoRE4INET::SRPTable::TalkerEntry> talkers);
/**
* set's the list of all ListenerEntries that should be configured
* @param listeners list of listeners
*/
void setListenerEntries(std::vector<CoRE4INET::SRPTable::ListenerEntry> listeners);
/**
* @returns a list containing all TalkerEntries that should be configured
*/
std::vector<CoRE4INET::SRPTable::TalkerEntry> getTalkerEntries();
/**
* @returns a list containing all ListenerEntries that should be configured
*/
std::vector<CoRE4INET::SRPTable::ListenerEntry> getListenerEntries();
/**
* adds a TalkerEntry to the list of TalkerEntries that should be configured
*/
void addTalkerEntry(CoRE4INET::SRPTable::TalkerEntry talker);
/**
* adds a ListenerEntry to the list of ListenerEntry that should be configured
*/
void addListenerEntry(CoRE4INET::SRPTable::ListenerEntry listener);
private:
/**
* TalkerEntries that should be configured
*/
std::vector<CoRE4INET::SRPTable::TalkerEntry> _talkers;
/**
* ListenerEntries that should be configured
*/
std::vector<CoRE4INET::SRPTable::ListenerEntry> _listeners;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTRUCTURES_SRP_NETCONFCONFIGSRP_H_ */
| 3,179
|
C++
|
.h
| 86
| 33.081395
| 87
| 0.730407
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,225
|
NetConfClientSessionInfoTCP.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/tcp/NetConfClientSessionInfoTCP.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_CLIENT_TCP_NETCONFSESSIONINFOTCP_H_
#define SDN4CORE_NETCONF_CLIENT_TCP_NETCONFSESSIONINFOTCP_H_
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfClientSessionInfo.h>
//INET
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
namespace SDN4CoRE {
/**
* TCP specific server session information.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfClientSessionInfoTCP: public NetConfClientSessionInfo {
public:
NetConfClientSessionInfoTCP(){
}
virtual ~NetConfClientSessionInfoTCP(){
}
/**
* returns the connection
* @return connID
*/
int getConnId() const {
return connID;
}
/**
* sets the connection id
* @param connId
*/
void setConnId(int connId) {
connID = connId;
}
/**
* returns the tcp socket
* @return socket
*/
inet::TCPSocket* getSocket() {
return socket;
}
/**
* sets a tcp socket
* @param socket
*/
void setSocket(inet::TCPSocket* socket) {
this->socket = socket;
}
private:
/**
* TCP socket for session.
*/
inet::TCPSocket *socket;
/**
* TCP Connection ID
*/
int connID;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_CLIENT_TCP_NETCONFSESSIONINFOTCP_H_ */
| 2,053
|
C++
|
.h
| 74
| 23.864865
| 78
| 0.696738
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,226
|
NetConfServerSessionInfoTCP.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/tcp/NetConfServerSessionInfoTCP.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_SERVER_TCP_NETCONFSESSIONINFOTCP_H_
#define SDN4CORE_NETCONF_SERVER_TCP_NETCONFSESSIONINFOTCP_H_
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfServerSessionInfo.h>
//INET
#include "inet/transportlayer/contract/tcp/TCPSocket.h"
namespace SDN4CoRE {
/**
* TCP specific server session information.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfServerSessionInfoTCP: public NetConfServerSessionInfo {
public:
NetConfServerSessionInfoTCP(){
}
virtual ~NetConfServerSessionInfoTCP(){
}
/**
* returns the connection
* @return connID
*/
int getConnId() const {
return connID;
}
/**
* sets the connection id
* @param connId
*/
void setConnId(int connId) {
connID = connId;
}
/**
* returns the tcp socket
* @return socket
*/
inet::TCPSocket* getSocket() {
return socket;
}
/**
* sets a tcp socket
* @param socket
*/
void setSocket(inet::TCPSocket* socket) {
this->socket = socket;
}
private:
/**
* TCP socket for session.
*/
inet::TCPSocket *socket;
/**
* TCP Connection ID
*/
int connID;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_SERVER_TCP_NETCONFSESSIONINFOTCP_H_ */
| 2,052
|
C++
|
.h
| 74
| 23.864865
| 78
| 0.696738
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,227
|
NetConfFilter.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/base/NetConfFilter.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_MESSAGES_NETCONFFILTER_H_
#define SDN4CORE_NETCONF_MESSAGES_NETCONFFILTER_H_
namespace SDN4CoRE {
class NetConfFilter {
public:
NetConfFilter();
NetConfFilter(const NetConfFilter& old){}
virtual ~NetConfFilter();
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
virtual unsigned int getByteSize();
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_MESSAGES_NETCONFFILTER_H_ */
| 1,198
|
C++
|
.h
| 32
| 35.125
| 78
| 0.75151
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,228
|
NetConfServerSessionInfo.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/base/NetConfServerSessionInfo.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_SERVER_BASE_NETCONFSESSIONINFO_H_
#define SDN4CORE_NETCONF_SERVER_BASE_NETCONFSESSIONINFO_H_
namespace SDN4CoRE {
/**
* Base class for protocol specific session information.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfServerSessionInfo {
public:
NetConfServerSessionInfo(){
}
virtual ~NetConfServerSessionInfo(){
}
/**
* get the current scessioId
* @return session id
*/
int getSessionId() {
return session_id;
}
/**
* set the sessionId
* @param _sessionId
*/
void setSessionId(int sessionId) {
session_id = sessionId;
}
private:
/**
* Session ID.
*/
int session_id;
// TODO save capabilities transmitted in NetConf hello message
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_SERVER_BASE_NETCONFSESSIONINFO_H_ */
| 1,595
|
C++
|
.h
| 53
| 26.773585
| 78
| 0.718485
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,229
|
NetConfConfig.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/base/NetConfConfig.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_MESSAGES_NETCONFCONFIG_H_
#define SDN4CORE_NETCONF_MESSAGES_NETCONFCONFIG_H_
//SDN4CoRE
#include <sdn4core/netconf/messages/NetConfOperation_m.h>
namespace SDN4CoRE {
/**
* Base class for all configuration data transferred in NetConf sessions.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfConfig : public NetConfConfig_Base{
public:
NetConfConfig();
virtual ~NetConfConfig();
/**
* copy constructor should be overritten to support copy of config data.
* @param old_obj the config to copy
*/
NetConfConfig (const NetConfConfig &old_obj) : NetConfConfig_Base(old_obj) {
};
/**
* Calculates the byte size of this config.
* @return the calculated byte size.
*/
virtual unsigned int getByteSize();
/**
* overrides message duplication to use class specific copy.
*/
virtual NetConfConfig_Base *dup() const override {return new NetConfConfig(*this);};
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_MESSAGES_NETCONFCONFIG_H_ */
| 1,770
|
C++
|
.h
| 48
| 34.020833
| 88
| 0.738471
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,230
|
NetConfClientSessionInfo.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastructures/base/NetConfClientSessionInfo.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_CLIENT_BASE_NETCONFSESSIONINFO_H_
#define SDN4CORE_NETCONF_CLIENT_BASE_NETCONFSESSIONINFO_H_
namespace SDN4CoRE {
/**
* Base class for protocol specific session information.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfClientSessionInfo {
public:
NetConfClientSessionInfo(){
}
virtual ~NetConfClientSessionInfo(){
}
/**
* get the current scessioId
* @return session id
*/
int getSessionId() {
return _sessionId;
}
/**
* set the sessionId
* @param _sessionId
*/
void setSessionId(int sessionId) {
_sessionId = sessionId;
}
/**
* get the application index
* @return _applicationIndex
*/
int getApplicationIndex() const {
return _applicationIndex;
}
/**
* set the application index
* @param applicationIndex
*/
void setApplicationIndex(int applicationIndex) {
_applicationIndex = applicationIndex;
}
private:
/**
* Session ID.
*/
int _sessionId;
/**
* Application connection gate index
*/
int _applicationIndex;
// TODO save capabilities transmitted in NetConf hello message
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_CLIENT_BASE_NETCONFSESSIONINFO_H_ */
| 2,026
|
C++
|
.h
| 71
| 24.535211
| 78
| 0.699794
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,231
|
NetConfRunningDataStore.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/store/running/NetConfRunningDataStore.h
|
//
// c Tobias Haugg, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTORES_STORE_RUNNING_NETCONFRUNNINGDATASTORE_H_
#define SDN4CORE_NETCONF_DATASTORES_STORE_RUNNING_NETCONFRUNNINGDATASTORE_H_
//Omnet
#include <omnetpp.h>
//STD
#include <vector>
//SDN4CoRE
#include <sdn4core/netconf/datastores/store/base/NetConfDataStoreBase.h>
#include <sdn4core/netconf/datastores/config/base/NetConfDataConfiguratorBase.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the running/active configuration of a device's Datatstore.
* All modifications done to this Datastore will be activated immediately.
* It supports all operations provided by the base class @see~NetConfDataStoreBase
*/
class NetConfRunningDataStore: public NetConfDataStoreBase {
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
*/
virtual bool validateConfig(NetConfConfig* config) override;
protected:
/**
* list of all active configurators
*/
std::vector<NetConfDataConfiguratorBase*> _configurators;
virtual void initialize() override;
};
}
#endif /* SDN4CORE_NETCONF_DATASTORES_CONFIG_OPENFLOW_OF_NETCONFCONFIGDATASTOREFLOWMOD_H_ */
| 2,766
|
C++
|
.h
| 61
| 42.344262
| 109
| 0.758633
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,232
|
NetConfCandidateDataStore.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/store/candidate/NetConfCandidateDataStore.h
|
//
// c Mohammad Fazel Soltani, Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef SDN4CORE_NETCONF_DATASTORES_STORE_CANDIDATE_NETCONFCANDIDATEDATASTORE_H_
#define SDN4CORE_NETCONF_DATASTORES_STORE_CANDIDATE_NETCONFCANDIDATEDATASTORE_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastores/store/base/NetConfDataStoreBase.h>
#include <sdn4core/netconf/datastores/store/running/NetConfRunningDataStore.h>
//AUTO-GENERATED MESSAGES
#include <sdn4core/netconf/messages/NetConfMessage_m.h>
#include <sdn4core/netconf/messages/NetConfOperation_m.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* The NetConfCandidateDataStore can be used when reconfigurations are supposed to be activated
* simultaneously. There fore this class holds a copy of a NetConfRunningDataStore's configuration that can be
* modified safely. When all modifications are done the NetConfCandidateDataStore can apply it's
* configuration to a NetConfRunningDataStore
*/
class NetConfCandidateDataStore: public NetConfDataStoreBase {
public:
virtual ~NetConfCandidateDataStore();
/**
* clear the configurations in this candidate data store
*/
void clear();
/**
* Apply changes to the running data store
* @param running the running data store
*/
bool applyTo(NetConfDataStoreBase* running);
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) override;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) override;
/**
* Validate the given config if it valid or not
*/
virtual bool validateConfig(NetConfConfig* config) override;
/**
* Sets the lock owner to the given session id if the candidate store does not have any changes
*
* @param lockHolderSessionId new lock holder session id
* @return true if it the lock was acquired
*/
virtual bool checkAndLock(int lockHolderSessionId) override;
protected:
/**
* The corresponding running Datatstore all reconfigurations will be applied to
*/
NetConfRunningDataStore* _runningStore;
/**
* configuration of the Datastore
*/
std::vector<NetConfConfig*> _configVector;
virtual void initialize() override;
};
} /* namespace SDN4CoRE */
#endif /* SDN4CORE_NETCONF_DATASTORES_CONFIG_CANDIDATE_NETCONFCANDIDATEDATASTORE_H_ */
| 3,777
|
C++
|
.h
| 84
| 41.285714
| 110
| 0.750204
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,233
|
NetConfDataStoreBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/store/base/NetConfDataStoreBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFDATASTOREBASE_H_
#define __SDN4CORE_NETCONFDATASTOREBASE_H_
//Omnet
#include <omnetpp.h>
//SDN4CoRE
#include <sdn4core/netconf/datastructures/base/NetConfConfig.h>
#include <sdn4core/netconf/datastructures/base/NetConfFilter.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* Contains the base module implementation and provides interface methods of a netconf config data store.
* NetConfConfigDataStore implementations execute netconf commands on the
* device such as get, copy and edit config commands.
* They are managed and dynamically created during runtime by
* @see~INetConfDataStoreManager modules.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfDataStoreBase : public cSimpleModule
{
public:
/**
* Creates a NetConfConfig from the current configuration data that only contains elements in the filter.
* @param filter the filter to be applied, if empty the whole config data set is returned
* @return the requested configuration data
*/
virtual NetConfConfig* getConfig(const NetConfFilter& filter) = 0;
/**
* Applies the changes in the config using the defaultOperation.
* @param defaultOperation Selects the default operation, one of @see ~NetConfOperation_Operation.
* @param errorOption Selects how to react on errors, one of @see ~NetConfOperation_ErrorOption.
* @param config The config to be applied
* @return true if the changes could be applied, false if an error occurred.
*/
virtual bool editConfig(int defaultOperation, int errorOption, NetConfConfig* config) = 0;
/**
* Validate the given config if it valid or not
*/
virtual bool validateConfig(NetConfConfig* config) = 0;
/**
* Check the lock indicator.
* @return the current lock state true locked, false unlocked
*/
virtual bool isLocked() {
return lockHolderSessionId >= 0;
}
/**
* Check whether the lock is held by the given session id.
* @return true if the lock is held by the given session id
*/
virtual bool isLockedBy(int lockHolderSessionId) {
return this->lockHolderSessionId == lockHolderSessionId;
}
virtual int getLockOwner() {
return lockHolderSessionId;
}
/**
* Removes the lock.
*/
virtual void unlock() {
this->lockHolderSessionId = -1;
}
/**
* Sets the lock owner to the given session id if not already locked.
*
* @param lockHolderSessionId new lock holder session id
* @return true if it the lock was acquired
*/
virtual bool checkAndLock(int lockHolderSessionId) {
if(lockHolderSessionId >= 0 && !isLocked()){
this->lockHolderSessionId = lockHolderSessionId;
return true;
}
return false;
}
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
/**
* Lock indicator of this config store (true locked, false unlocked)
*/
int lockHolderSessionId = -1;
/**
*
*/
static simsignal_t editConfigOkSignal;
/**
*
*/
static simsignal_t editConfigErrorSignal;
};
} /* namespace SDN4CoRE */
#endif
| 4,026
|
C++
|
.h
| 109
| 32.422018
| 109
| 0.702848
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,234
|
NetConfDataStoreManagerBase.h
|
CoRE-RG_SDN4CoRE/src/sdn4core/netconf/datastores/manager/base/NetConfDataStoreManagerBase.h
|
//
// c Timo Haeckel, for HAW Hamburg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __SDN4CORE_NETCONFDATASTOREMANAGERBASE_H_
#define __SDN4CORE_NETCONFDATASTOREMANAGERBASE_H_
//STD
#include <omnetpp.h>
#include <string>
#include <unordered_map>
//CoRE4INET
#include "core4inet/scheduler/period/Period.h"
//SDN4CoRE
#include <sdn4core/netconf/datastores/store/running/NetConfRunningDataStore.h>
#include <sdn4core/netconf/datastores/store/candidate/NetConfCandidateDataStore.h>
#include <sdn4core/netconf/datastructures/transactionModel/NetConfConfigCommitTimestamp.h>
//AUTO-GENERATED MESSAGES
#include <sdn4core/netconf/messages/NetConfMessage_m.h>
#include <sdn4core/netconf/messages/NetConfOperation_m.h>
using namespace omnetpp;
namespace SDN4CoRE {
/**
* forward declaration of NetConfDataStoreManagerBase
*/
class NetConfServerBase;
/**
* Base implementation of a netconf config store manager.
* NetConfDataStoreManger implementations handle NetConf configuration and
* state operations for a specific device.
*
* It uses a @see ~NetConfStateDataStore to handle state operations and a map
* @see~ NetConfConfigDataStore to handle config operations.
* Device specific implementations should also use device specific types for
* there data stores.
*
* @author Timo Haeckel, for HAW Hamburg
*/
class NetConfDataStoreManagerBase : public cSimpleModule , public cListener
{
public:
virtual ~NetConfDataStoreManagerBase();
protected:
virtual void initialize() override;
virtual void handleParameterChange(const char* parname) override;
virtual void handleMessage(cMessage *msg) override;
virtual void receiveSignal(cComponent *source, simsignal_t signalID, long l, cObject *details) override;
/**
* Creates an rpc reply element containing the data.
* @param config the config data to encapsulate
* @return the NetConf_RPCReplyElement_Data
*/
virtual NetConf_RPCReplyElement* createRPCReplyElement_Data(
NetConfConfig* config);
/**
* Creates an rpc reply element containing the error message.
* @param error_type Defines the conceptual layer that the error occurred.
* One of @see ~NetConf_RPCReplyElement_Error_Type
* @param error_tag Contains a string identifying the error condition.
* @param error_severity Contains an enum identifying the error severity, as
* determined by the device. One of @see ~NetConf_RPCReplyElement_Error_Severity
* @param error_app_tag Contains a string identifying the data-model-specific
* or implementation-specific error condition, if one exists.
* @return the NetConf_RPCReplyElement_Error
*/
virtual NetConf_RPCReplyElement* createRPCReplyElement_Error(
int error_type, const char * error_tag, int error_severity,
const char * error_app_tag);
/**
* Creates an rpc reply element containing OK.
* @return the NetConf_RPCReplyElement_Ok
*/
virtual NetConf_RPCReplyElement* createRPCReplyElement_Ok();
/**
* Handles a NetConfOperation_GetConfig message, forwards it to the correct
* config store and creates a reply.
* @param operation the NetConfOperation_GetConfig message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleGetConfig(NetConfOperation* operation);
/**
* Handles a NetConfOperation_EditConfig message, forwards it to the correct
* config store and creates a reply.
* @param operation the NetConfOperation_EditConfig message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleEditConfig(NetConfOperation* operation);
/**
* Handles a NetConfOperation_CopyConfig message, forwards it to the correct
* config store and creates a reply.
* @param operation the NetConfOperation_CopyConfig message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleCopyConfig(NetConfOperation* operation);
/**
* Handles a NetConfOperation_DeleteConfig message, forwards it to the correct
* config store and creates a reply.
* @param operation the NetConfOperation_DeleteConfig message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleDeleteConfig(NetConfOperation* operation);
/**
* Handles a NetConfOperation_Get message, forwards it to the data
* store and creates a reply.
* @param operation the NetConfOperation_Get message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleGet(NetConfOperation* operation);
/**
* Handles a NetConfOperation_Lock message, forwards it to the data
* store and creates a reply.
* @param operation the NetConfOperation_Lock message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleLock(NetConfOperation* operation);
/**
* Handles a NetConfOperation_Unlock message, forwards it to the data
* store and creates a reply.
* @param operation the NetConfOperation_Unlock message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleUnlock(NetConfOperation* operation);
/**
* Handles a NetConfOperation_Commit message, forwards it to the data
* store and creates a reply.
* @param operation the NetConfOperation_Commit message
* @return a NetConf_RPCReplyElement
*/
virtual NetConf_RPCReplyElement* handleCommit(NetConfOperation* operation);
/**
* verifies the lock by the given sessionId
* @param datastore the given config data store
* @param operation the NetConf operation which has the sessionId
* @return true if the data store is locked by the given sessionId or unlocked, else false
*/
bool verifyLock(NetConfDataStoreBase* datastore, NetConfOperation* operation);
/**
* Schedules the timed commit
* @param commit the commit operation
*/
virtual void scheduleTimedCommit(NetConfOperation_Commit* commit);
/**
* Executes the commit
* @return the result of commit execution
*/
virtual bool executeCommit();
/**
* checks if it is a valid commit timestamp
* @return true, if it is valid, else false
*/
bool hasCommitTimestamp();
/**
* sets the commitOperation and deletes the old commitOperation
* @param commitOperation the NetConf operation
*/
void setCommitOperation(NetConfOperation_Commit* commitOperation);
/**
* resets the commit operation and timestamp
*/
void resetCommitTimestamp();
/**
* the commit operation
*/
NetConfOperation_Commit* _commitOperation = nullptr;
/**
* the commit timestamp
*/
NetConfConfigCommitTimestamp::CommitTimestamp_t _commitTimestamp;
/**
* the period of the scheduler
*/
std::vector<CoRE4INET::Period*> _periods;
/**
* the new cycle signal which is to subscribe
*/
simsignal_t _newCycleSignal;
/**
* Cached reference to the NetConf server.
*/
NetConfServerBase* _netConfServer;
/**
* Cached parameter if the status should be displayed
*/
bool _displayStatus;
/**
* Running configuration data store
*/
NetConfRunningDataStore* _runningStore;
/**
* Candidate configuration data store
*/
NetConfCandidateDataStore* _candidateStore;
/**
* Gate name (@directIn) for request inputs in data stores
*/
static const char REQUEST_IN_GATE_NAME []; // = "requestIn";
/**
* Gate name (@directIn) for response inputs to NetConf server
*/
static const char RESPONSE_OUT_GATE_NAME []; // = "responseIn";
static simsignal_t commitExecutionSignal;
static simsignal_t editConfigSignal;
};
} // namespace SDN4CoRE
#endif
| 8,789
|
C++
|
.h
| 216
| 35.930556
| 109
| 0.713165
|
CoRE-RG/SDN4CoRE
| 30
| 13
| 3
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.