diff --git a/api/check_status.py b/api/check_status.py deleted file mode 100644 index e8b63500..00000000 --- a/api/check_status.py +++ /dev/null @@ -1,52 +0,0 @@ -import os -import json -import boto3 - -# Create .cache directory if it doesn't exist -os.makedirs('.cache', exist_ok=True) - -def cache(name, value): - cache_file = f'.cache/{name}' - if not os.path.isfile(cache_file): - with open(cache_file, 'w') as f: - f.write(value) - -# Initialize Boto3 SSM client -ssm = boto3.client('ssm') - -# List commands from AWS SSM -response = ssm.list_commands() - -cache("aws_ssm_list_commands", response) - -# Retrieve commands -print(response) -commands = response["Commands"] -run_ids = [cmd['CommandId'] for cmd in commands] -print(f"RUNIDS: {run_ids}") - -# Check the status of each command -for command in commands: - #print(command) - command_id = command['CommandId'] - status = command['Status'] - #eG: command= {'CommandId': '820dcf47-e8d7-4c23-8e8a-bc64de2883ff', 'DocumentName': 'AWS-RunShellScript', 'DocumentVersion': '$DEFAULT', 'Comment': '', 'ExpiresAfter': datetime.datetime(2024, 12, 13, 12, 41, 24, 683000, tzinfo=tzlocal()), 'Parameters': {'commands': ['sudo su - -c "tail /var/log/cloud-init-output.log"']}, 'InstanceIds': [], 'Targets': [{'Key': 'instanceids', 'Values': ['i-073378237c5a9dda1']}], 'RequestedDateTime': datetime.datetime(2024, 12, 13, 10, 41, 24, 683000, tzinfo=tzlocal()), 'Status': 'Success', 'StatusDetails': 'Success', 'OutputS3Region': 'us-east-1', 'OutputS3BucketName': '', 'OutputS3KeyPrefix': '', 'MaxConcurrency': '50', 'MaxErrors': '0', 'TargetCount': 1, 'CompletedCount': 1, 'ErrorCount': 0, 'DeliveryTimedOutCount': 0, 'ServiceRole': '', 'NotificationConfig': {'NotificationArn': '', 'NotificationEvents': [], 'NotificationType': ''}, 'CloudWatchOutputConfig': {'CloudWatchLogGroupName': '', 'CloudWatchOutputEnabled': False}, 'TimeoutSeconds': 3600, 'AlarmConfiguration': {'IgnorePollAlarmFailure': False, 'Alarms': []}, 'TriggeredAlarms': []}], 'ResponseMetadata': {'RequestId': '535839c4-9b87-4526-9c01-ed57f07d21ef', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Fri, 13 Dec 2024 16:58:53 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2068', 'connection': 'keep-alive', 'x-amzn-requestid': '535839c4-9b87-4526-9c01-ed57f07d21ef'}, 'RetryAttempts': 0}} - - if status == "Success": - print(f"Check logs of {command_id}") - # use ssm to fetch logs using CommandId - - # Assuming you have the command_id from the previous command output - command_id = command['CommandId'] - instance_id = command['Targets'][0]['Values'][0] # Get the instance ID - - # Fetching logs using CommandId - log_response = ssm.get_command_invocation( - CommandId=command_id, - InstanceId=instance_id - ) - print(log_response['StandardOutputContent']) # Output logs - print(log_response['StandardErrorContent']) # Error logs (if any) - print(f"aws ssm start-session --target {instance_id}") - - diff --git a/api/test_endpoints.py b/api/test_endpoints.py new file mode 100644 index 00000000..cfae9d71 --- /dev/null +++ b/api/test_endpoints.py @@ -0,0 +1,61 @@ +import time +import requests +import boto3 +#from dateutil import tz + + +def parse_command_id(send_command_output): + return send_command_output['Command']['CommandId'] + +def main(): + ec2_client = boto3.client('ec2') + ssm_client = boto3.client('ssm') + + # Get the list of instance IDs and their states + instances_response = ec2_client.describe_instances() + + for reservation in instances_response['Reservations']: + for instance in reservation['Instances']: + state = instance['State']["Name"] + instance_id = instance['InstanceId'] + if state == 'running': + + ip = instance["PublicIpAddress"] + BASE_URL=f"http://{ip}:80/v1/" + print(f"Starting command for instance: {instance_id} {BASE_URL}") + try: + response = requests.get(f"{BASE_URL}/docs", timeout=3) + print(response) + except Exception as exp: + print(BASE_URL,exp) + + # {'AmiLaunchIndex': 0, 'ImageId': 'ami-0e2c8caa4b6378d8c', 'InstanceId': 'i-0d41e4263f40babec', 'InstanceType': 't3.small', 'KeyName': 'mdupont-deployer-key', 'LaunchTime': datetime.datetime(2024, 12, 14, 16, 1, 50, tzinfo=tzutc()), + # 'Monitoring': {'State': 'disabled'}, + # 'Placement': {'AvailabilityZone': 'us-east-1a', 'GroupName': '', 'Tenancy': 'default'}, 'PrivateDnsName': 'ip-10-0-4-18.ec2.internal', 'PrivateIpAddress': '10.0.4.18', 'ProductCodes': [], + #'PublicDnsName': 'ec2-3-228-14-220.compute-1.amazonaws.com', + #'PublicIpAddress': '3.228.14.220', + # 'State': {'Code': 16, 'Name': 'running'}, 'StateTransitionReason': '', 'SubnetId': 'subnet-057c90cfe7b2e5646', 'VpcId': 'vpc-04f28c9347af48b55', 'Architecture': 'x86_64', + # 'BlockDeviceMappings': [{'DeviceName': '/dev/sda1', + # 'Ebs': {'AttachTime': datetime.datetime(2024, 12, 14, 16, 1, 50, tzinfo=tzutc()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-0257131dd2883489b'}}], 'ClientToken': 'b5864f17-9e56-2d84-fc59-811abf8e6257', 'EbsOptimized': False, 'EnaSupport': True, 'Hypervisor': 'xen', 'IamInstanceProfile': + # {'Arn': 'arn:aws:iam::767503528736:instance-profile/swarms-20241213150629570500000003', 'Id': 'AIPA3FMWGOMQKC4UE2UFO'}, 'NetworkInterfaces': [ + # {'Association': + # {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-3-228-14-220.compute-1.amazonaws.com', 'PublicIp': '3.228.14.220'}, 'Attachment': + # {'AttachTime': datetime.datetime(2024, 12, 14, 16, 1, 50, tzinfo=tzutc()), 'AttachmentId': 'eni-attach-009b54c039077324e', 'DeleteOnTermination': True, 'DeviceIndex': 0, 'Status': 'attached', 'NetworkCardIndex': 0}, 'Description': '', 'Groups': [ + # {'GroupName': 'swarms-20241214133959057000000001', 'GroupId': 'sg-03c9752b62d0bcfe4'}], 'Ipv6Addresses': [], 'MacAddress': '02:c9:0b:47:cb:df', 'NetworkInterfaceId': 'eni-08661c8b4777c65c7', 'OwnerId': '767503528736', 'PrivateDnsName': 'ip-10-0-4-18.ec2.internal', 'PrivateIpAddress': '10.0.4.18', 'PrivateIpAddresses': [ + # {'Association': + # {'IpOwnerId': 'amazon', 'PublicDnsName': 'ec2-3-228-14-220.compute-1.amazonaws.com', 'PublicIp': '3.228.14.220'}, 'Primary': True, 'PrivateDnsName': 'ip-10-0-4-18.ec2.internal', 'PrivateIpAddress': '10.0.4.18'}], 'SourceDestCheck': True, 'Status': 'in-use', 'SubnetId': 'subnet-057c90cfe7b2e5646', 'VpcId': 'vpc-04f28c9347af48b55', 'InterfaceType': 'interface'}], 'RootDeviceName': '/dev/sda1', 'RootDeviceType': 'ebs', 'SecurityGroups': [ + # {'GroupName': 'swarms-20241214133959057000000001', 'GroupId': 'sg-03c9752b62d0bcfe4'}], 'SourceDestCheck': True, 'Tags': [ + # {'Key': 'Name', 'Value': 'swarms-size-t3.small'}, + # {'Key': 'aws:ec2launchtemplate:id', 'Value': 'lt-0e618a900bd331cfe'}, + # {'Key': 'aws:autoscaling:groupName', 'Value': 'swarms-size-t3.small-2024121416014474500000002f'}, + # {'Key': 'aws:ec2launchtemplate:version', 'Value': '1'}], 'VirtualizationType': 'hvm', 'CpuOptions': + # {'CoreCount': 1, 'ThreadsPerCore': 2}, 'CapacityReservationSpecification': + # {'CapacityReservationPreference': 'open'}, 'HibernationOptions': + # {'Configured': False}, 'MetadataOptions': + # {'State': 'applied', 'HttpTokens': 'required', 'HttpPutResponseHopLimit': 2, 'HttpEndpoint': 'enabled', 'HttpProtocolIpv6': 'disabled', 'InstanceMetadataTags': 'disabled'}, 'EnclaveOptions': + # {'Enabled': False}, 'BootMode': 'uefi-preferred', 'PlatformDetails': 'Linux/UNIX', 'UsageOperation': 'RunInstances', 'UsageOperationUpdateTime': datetime.datetime(2024, 12, 14, 16, 1, 50, tzinfo=tzutc()), 'PrivateDnsNameOptions': + # {'HostnameType': 'ip-name', 'EnableResourceNameDnsARecord': False, 'EnableResourceNameDnsAAAARecord': False}, 'MaintenanceOptions': + # {'AutoRecovery': 'default'}, 'CurrentInstanceBootMode': 'uefi'} + +if __name__ == "__main__": + main()