Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions server/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DEBUG_FLAG=True
34 changes: 21 additions & 13 deletions server/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from .models import LibraryRegistration
from webcligui_api import ParameterList, ParameterOptionsToList, ParameterPreference, ParameterStringValue
# from webcligui_api import ParameterList, ParameterOptionsToList, ParameterPreference, ParameterStringValue

libraryApis = []
library2Idx = {}

def instantiateLibraryModule(obj):
module = importlib.import_module(obj.module_path)
cls = getattr(module, obj.class_name)
print(f"api.py-- cls={cls} obj={obj} class_name={obj.class_name} module={module} ")
libraryAPIImpl = cls()
return libraryAPIImpl

Expand All @@ -24,9 +25,11 @@ def load_library_apis():
return

for idx, obj in enumerate(LibraryRegistration.objects.all()):
print(f"api.py-- idx={idx} obj={obj} name={obj.library_name} module={obj.module_path} ")
libraryAPIImpl = instantiateLibraryModule(obj)
libraryApis.append(libraryAPIImpl)
library2Idx[obj.library_name] = idx
# library2Idx[obj.module_path] = idx
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it is commented out why don't we remove this line?


def to_json_safe(obj):
if isinstance(obj, Enum):
Expand Down Expand Up @@ -69,7 +72,7 @@ def get_description(request):
libraryApiImpl = getLibraryApi(libraryName)
if not libraryApiImpl:
errMsg = f'Libraryname "{libraryName}" not known!'
print('get_description():', errMsg)
print('api.py--get_description():', errMsg)
return HttpResponseBadRequest(errMsg)

operationBranch = body["operationBranch"][1:]
Expand All @@ -84,9 +87,10 @@ def get_parameters(request):
body = json.loads(request.body)
libraryName = body["operationBranch"][0]
libraryApiImpl = getLibraryApi(libraryName)
print(f"api.py--get_parameters(): libraryName={libraryName}")
if not libraryApiImpl:
errMsg = f'Libraryname "{libraryName}" not known!'
print('get_parameters():', errMsg)
print('api.py--get_parameters():', errMsg)
return HttpResponseBadRequest(errMsg)

operationBranch = body["operationBranch"][1:]
Expand All @@ -100,16 +104,20 @@ def get_parameters(request):
@permission_classes([AllowAny])
def submit_operation(request):
body = json.loads(request.body)
libraryName = body["operationBranch"][0]
libraryApiImpl = getLibraryApi(libraryName)
if not libraryApiImpl:
errMsg = f'Libraryname "{libraryName}" not known!'
print('api.py--submit_operation():', errMsg)
return HttpResponseBadRequest(errMsg)

operationBranch = body["operationBranch"][1:]
command = body['command']
servers = body["servers"]

print(f"api.py--submit_operation(): libraryName={libraryName}, operationBranch={operationBranch}")
print(f"command={command}, servers={servers}")

result = libraryApiImpl.submitOperation(body['operationBranch'], command, servers)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry, but I don't see the use of this function being called in the libraryApi. The libraryApi is purely meant to pass in the different operations to webCliGui. When the operation is selected it should just run in our server. I don't know what you need to do to actually run the operation (can't it just run in Django since it is fully operational in bisos?). However, if there is some reason that you need to run it in your environment then I would like to run it in a separate library that you created. Not in the libraryApi. The reason why I don't want it is that we are going to provide the service to T-Mobile. Therefore we need to be fully responsible for running the operation, not T-Mobile themselves. Giving a library to them so they could call it would defeat that purpose and would make our work counterproductive. We need to call that library ourselves.


print('command:', command, 'servers:', servers)
fullCommand = command + ['localhost']
print('fullCommand:', fullCommand)
try:
subprocess.run(fullCommand, check=True)
except Exception as exc:
print('Exception:', exc)
return HttpResponseServerError(str(exc));

return HttpResponse('OK')
return JsonResponse(result, safe=False)
8 changes: 8 additions & 0 deletions server/djangoProc.spcs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ def examples_spcs() -> None:

cs.examples.menuSection(f'*Register csLib*')
literal(f"manage.py register_library csLib csLib LibraryAPIImpl --description 'Command Services Library'")
literal(f"manage.py register_library static bisos.csPlayer.drf_csPlayer_static LibraryAPIImpl --description 'A Static CSXU Library For Testing'")
literal(f"manage.py register_library pip:bisos3 bisos.csPlayer.drf_csPlayer_pipBisos3 LibraryAPIImpl --description 'pip bisos3 CSXUs'")
literal(f"manage.py register_library pip:dev-bisos3 bisos.csPlayer.drf_csPlayer_pipDevBisos3 LibraryAPIImpl --description 'pip dev-bisos3 CSXUs'")
literal(f"manage.py register_library pipx bisos.csPlayer.drf_csPlayer_pipx LibraryAPIImpl --description 'pipx Packages and CSXUs'")
literal(f"manage.py register_library modules:facter bisos.csPlayer.drf_modPlayer_facter LibraryAPIImpl --description 'CSXU Modules for facterModule.cs'")
literal(f"manage.py register_library modules:soncli bisos.csPlayer.drf_modPlayer_soncli LibraryAPIImpl --description 'Uploadable Modules for soncli.cs'")

cs.examples.menuSection(f'*Virtual Domain Deployment Preparations*')
literal(f"sudo chown {userName}:www-data .") # Make the current directory writable by www-data
Expand All @@ -66,6 +72,8 @@ def examples_spcs() -> None:
cmnd('dotEnv', wrapper="rm .env ; ", comment="# Create .env with DEBUG_FLAG=True for development")
cmnd('bxDjango_report')
cmnd('bxDjango_fullUpdate')
literal(f"(pushd {gitClonesBaseDir}/webCliGui/webcligui_api && pip install -e .)")
literal(f"(pushd {gitClonesBaseDir}/csLib && pip install -e .)")

class bxDjango_fullUpdate(cs.Cmnd):
cmndParamsMandatory = [ ]
Expand Down
10 changes: 10 additions & 0 deletions server/webCliGui/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'drf_spectacular',
'drf_spectacular_sidecar', # Optional, for serving static files
'api',
]

Expand Down Expand Up @@ -136,4 +138,12 @@
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
],
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

SPECTACULAR_SETTINGS = {
'TITLE': 'Your Project API',
'DESCRIPTION': 'Documentation for Your Project API',
'VERSION': '1.0.0',
# Other settings like authentication can be added here
}
15 changes: 13 additions & 2 deletions server/webCliGui/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,19 @@
"""
from django.contrib import admin
from django.urls import path, include
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView, SpectacularRedocView

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include("api.urls")),
path('admin/', admin.site.urls),
path('api/', include("api.urls")),

# OpenAPI 3 Schema
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),

# Optional: Swagger UI web interface
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),

# Optional: ReDoc web interface
path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),

]
3 changes: 1 addition & 2 deletions src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ const App = () => {

return (
<div className="flex flex-col p-5 pt-3 max-w-[1325px]">

<h3 className="pb-4">Web UI Command Services Executor</h3>
{/* <h3 className="pb-4">Web UI Command Services Executor</h3> */}

<Tabs defaultActiveKey="createTask"
mountOnEnter
Expand Down
33 changes: 24 additions & 9 deletions src/components/CreateTask.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import Button from "./Button";
import { FetchState } from "../utils/fetchData";
import WaitCircle from "./WaitCircle";

const CreationSteps = () => {
interface CreationStepsProps {
operationPos: string | null;
}

const CreationSteps = ({ operationPos }: CreationStepsProps) => {
const {
taskCreationStep,
isNextStepValid,
Expand All @@ -23,7 +27,9 @@ const CreationSteps = () => {
if (taskCreationStep !== TaskCreationSteps.Preview) {
setNextTaskCreationStep(taskCreationStep + 1);
} else {
submitOperation();
if (operationPos) {
submitOperation(operationPos);
}
}
};

Expand Down Expand Up @@ -66,9 +72,10 @@ const CreationSteps = () => {

interface OperationSelectionProps {
isVisible: boolean;
onSelectOperation: (pos: string) => void;
}

const OperationSelection = ({ isVisible }: OperationSelectionProps) => {
const OperationSelection = ({ isVisible, onSelectOperation }: OperationSelectionProps) => {
const {
taskTrees,
selectedOperationBranch,
Expand All @@ -78,7 +85,9 @@ const OperationSelection = ({ isVisible }: OperationSelectionProps) => {
} = useDataStore(state => state.createTask);

const onSelect = (selectedKeys: React.Key[], selectData: any) => {
setSelectedOperation(selectData.node.pos);
const pos = selectData.node.pos;
onSelectOperation(pos);
setSelectedOperation(pos);
};

let selectedOperation: Operation | null = null;
Expand Down Expand Up @@ -362,12 +371,17 @@ const Preview = ({
);
};

const CreationViews = () => {
interface CreationViewsProps {
operationPos: string | null;
setOperationPos: (pos: string) => void;
}

const CreationViews = ({ operationPos, setOperationPos }: CreationViewsProps) => {
const { taskCreationStep } = useDataStore(state => state.createTask);

return (
<>
<OperationSelection isVisible={taskCreationStep === TaskCreationSteps.OperatorSelection} />
<OperationSelection isVisible={taskCreationStep === TaskCreationSteps.OperatorSelection} onSelectOperation={setOperationPos} />
<OperationParameters isVisible={taskCreationStep === TaskCreationSteps.Parameters} />
<SelectServers isVisible={taskCreationStep === TaskCreationSteps.ServersSelection} />
<Preview isVisible={taskCreationStep === TaskCreationSteps.Preview} />
Expand All @@ -376,16 +390,17 @@ const CreationViews = () => {
};

const CreateTask = () => {
const { getLibraryOperators } = useDataStore(state => state.createTask);
const { getLibraryOperators } = useDataStore(state => state.createTask);
const [operationPos, setOperationPos] = React.useState<string | null>(null);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a no-no: the useState is never used. All the data is stored in the dataStore so the useState is of no use (except for small local variables like the tabs - these are not stored in the datastore). You can see it in CreateViews where the selected operation is stored in the dataStore using setSelectedOperation. Please remove this and all references to it.


useEffect(() => {
getLibraryOperators();
}, []);

return (
<div className="flex flex-col">
<CreationSteps />
<CreationViews />
<CreationSteps operationPos={operationPos} />
<CreationViews operationPos={operationPos} setOperationPos={setOperationPos} />
</div>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/store/createTaskIf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ export interface CreateTaskIf {
loadParameters: () => Promise<FetchStatus>;
setParameterValue: (parameterBranch: number[], value: ParameterValue) => void;
getExecuteCommand: () => string[] | null;
submitOperation: () => void;
submitOperation: (operationPos: string) => Promise<FetchStatus>;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The operationPos is already in the dataStore in createTask.selectedOperationBranch. Please remove this parameter operationPos.

}
12 changes: 9 additions & 3 deletions src/store/dataStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,9 +425,14 @@ const doGetExecuteCommand = (get: GetFunction) => {
return [operation.name, ...params];
}

const doSubmitOperation = async (get: GetFunction, set: SetFunction) => {
const doSubmitOperation = async (operationPos: string, get: GetFunction, set: SetFunction) => {
const cmd = doGetExecuteCommand(get) as string[];

const operationBranch = getOperationBranch(operationPos, get().createTask.taskTrees);
if (!operationBranch) {
return FetchState.Idle;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The operationBranch is available already in the dataStore. Please get it with get().createTask.selectedOperationBranch. You don't need to pass in operationPos.

const setFetchStatus = (stat: FetchStatus) =>
set(state => { state.createTask.submitOperationFetchAndError.fetchStatus = stat; },
false, 'submitOperationFetchStatus');
Expand All @@ -439,14 +444,15 @@ const doSubmitOperation = async (get: GetFunction, set: SetFunction) => {
}, false, 'submitOperationError');

interface SubmitOperation {
operationBranch: string[];
command: string[];
servers: string[];
}

return await fetchData<string, SubmitOperation>(
'/api/submit-operation',
{
postData: { command: cmd, servers: [WEB_CLI_GUI_SERVER] },
postData: { operationBranch: operationBranch, command: cmd, servers: [WEB_CLI_GUI_SERVER] },
setFetchStatus,
setError,
}
Expand Down Expand Up @@ -489,7 +495,7 @@ export const useDataStore = create<DataStoreIf>()(
loadParameters: async () => await doLoadParameters(get, set),
setParameterValue: (parameterBranch: number[], value: ParameterValue) => doSetParameterValue(parameterBranch, value, get, set),
getExecuteCommand: () => doGetExecuteCommand(get),
submitOperation: () => doSubmitOperation(get, set),
submitOperation: (operationPos: string) => doSubmitOperation(operationPos, get, set),
}
})), {
name: 'DataStore',
Expand Down
4 changes: 4 additions & 0 deletions webcligui_api/src/webcligui_api/library_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ def getDescription(self, operationBranch: list[str]) -> str:
@abstractmethod
def getParameters(self, operationBranch: list[str]) -> ParameterData:
pass

@abstractmethod
def submitOperation(self, operationBranch: list[str], command: list[str], servers: list[str]):
pass
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my comment above in api.py. This method is counterproductive.

6 changes: 3 additions & 3 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ export default {
historyApiFallback: true,
hot: true,
host: "0.0.0.0",
port: 9002,
port: 25002,
proxy: [
{
context: ['/api', '/admin', '/static'],
target: 'http://127.0.0.1:5000',
target: 'http://127.0.0.1:23501',
secure: false,
changeOrigin: true,
}
Expand All @@ -99,4 +99,4 @@ export default {
]
})
],
};
};