Skip to content

Enable and disable Rules #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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 .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ MANIFEST
manual_dist/**
sagemaker_run_notebook/cloudformation.yml
docs/build/**
.DS_Store
10 changes: 8 additions & 2 deletions container/build_and_push.sh
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ region=$(aws configure get region)
region=${region:-us-west-2}
echo "Region ${region}"

if [[ $region == cn-* ]]
then
amazon_extension="amazonaws.com.cn"
else
amazon_extension="amazonaws.com"
fi

fullname="${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest"
fullname="${account}.dkr.ecr.${region}.${amazon_extension}/${image}:latest"

# If the repository doesn't exist in ECR, create it.

Expand All @@ -73,7 +79,7 @@ then
# Get the login command from ECR and execute it directly
$(aws ecr get-login --region ${region} --no-include-email)
else
aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com
aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.${amazon_extension}
fi

# Build the docker image locally with the image name and then push it to ECR
Expand Down
39 changes: 38 additions & 1 deletion labextension/src/components/RuleList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@ export class RulesList extends React.Component<RuleListProps, RuleListState> {
rule.image,
rule.instance,
rule.role,
rule.state,
// rule.state,
<a key="state" onClick={this.toggleState(rule.name, rule.state)} className={tableLinkClass}>
{rule.state}
</a>,
<a key={rule.name} onClick={this.deleteRule(rule.name)} className={tableLinkClass}>
Delete
</a>,
Expand Down Expand Up @@ -96,6 +99,40 @@ export class RulesList extends React.Component<RuleListProps, RuleListState> {
return <SimpleTablePage title="Schedule and Event Rules">{content}</SimpleTablePage>;
}

private toggleState(rule: string, state: string) {
return async (): Promise<boolean> => {
console.log(`toggle rule ${rule} state from ${state}`);
if (!['DISABLED', 'ENABLED'].includes(state)) {
console.log(`unknown state: ${state}`);
return;
}
const settings = ServerConnection.makeSettings();
const response = await ServerConnection.makeRequest(
URLExt.join(settings.baseUrl, 'sagemaker-scheduler', 'schedule', rule),
{ method: 'PATCH', body: JSON.stringify({ action: state === 'DISABLED' ? 'enable' : 'disable' }) },
settings,
);

if (!response.ok) {
const error = (await response.json()) as ErrorResponse;
let errorMessage: string;
if (error.error) {
errorMessage = error.error.message;
} else {
errorMessage = JSON.stringify(error);
}
showDialog({
title: 'Error toggling schedule state',
body: <p>{errorMessage}</p>,
buttons: [Dialog.okButton({ label: 'Close' })],
});
return;
}
this.props.model.refresh();
return true;
};
}

private deleteRule(rule: string) {
return async (): Promise<boolean> => {
const deleteBtn = Dialog.warnButton({ label: 'Delete' });
Expand Down
2 changes: 2 additions & 0 deletions sagemaker_run_notebook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
create_lambda_role,
schedule,
unschedule,
enable_schedule,
disable_schedule,
describe_schedule,
describe_schedules,
list_schedules,
Expand Down
28 changes: 27 additions & 1 deletion sagemaker_run_notebook/run_notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,7 +982,7 @@ def unschedule(rule_name, session=None):
prefixed_rule_name = RULE_PREFIX + rule_name

session = ensure_session(session)
events = boto3.client("events")
events = session.client("events")
lambda_ = session.client("lambda")

try:
Expand All @@ -1000,6 +1000,32 @@ def unschedule(rule_name, session=None):

events.delete_rule(Name=prefixed_rule_name)

def enable_schedule(rule_name, session=None):
"""Enable an existing notebook schedule rule.

Args:
rule_name (str): The name of the rule for CloudWatch Events (required).
session (boto3.Session): The boto3 session to use. Will create a default session if not supplied (default: None).
"""
prefixed_rule_name = RULE_PREFIX + rule_name

session = ensure_session(session)
events = session.client("events")
events.enable_rule(Name=prefixed_rule_name)

def disable_schedule(rule_name, session=None):
"""Disable an existing notebook schedule rule.

Args:
rule_name (str): The name of the rule for CloudWatch Events (required).
session (boto3.Session): The boto3 session to use. Will create a default session if not supplied (default: None).
"""
prefixed_rule_name = RULE_PREFIX + rule_name

session = ensure_session(session)
events = session.client("events")
events.disable_rule(Name=prefixed_rule_name)


def describe_schedules(n=0, rule_prefix=None, session=None):
"""A generator that returns descriptions of all the notebook schedule rules
Expand Down
18 changes: 17 additions & 1 deletion sagemaker_run_notebook/server_extension/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def load_params(self, required):
try:
data = json.loads(self.request.body.decode("utf-8"))

if not self.required_params(data, ["image", "input_path", "notebook"]):
if not self.required_params(data, required):
return None
else:
return data
Expand Down Expand Up @@ -296,6 +296,22 @@ def delete(self, rule_name):
except botocore.exceptions.BotoCoreError as e:
self.botocore_error_response(e)

def patch(self, rule_name):
"""Enable or disable a rule"""
try:
data = self.load_params(["action"])
if data is None:
return

if data['action'] == 'enable':
run.enable_schedule(rule_name=rule_name)
elif data['action'] == 'disable':
run.disable_schedule(rule_name=rule_name)
except botocore.exceptions.ClientError as e:
self.client_error_response(e)
except botocore.exceptions.BotoCoreError as e:
self.botocore_error_response(e)


class InvokeHandler(BaseHandler):
def post(self):
Expand Down