15
15
16
16
import os
17
17
import json
18
- import click
18
+ import sys
19
19
import time
20
20
import logging
21
+ import httpx
22
+ import click
21
23
import ibm_vpc
22
24
from ibm_vpc import VpcV1
23
25
from ibm_cloud_sdk_core .authenticators import IAMAuthenticator
@@ -50,6 +52,45 @@ def vpc_client():
50
52
51
53
ignore_group = ['tethys' , 'jbmh-locate' ]
52
54
55
+ def get_iam_token ():
56
+ try :
57
+ hdrs = { 'Accept' : 'application/json' , 'Content-Type' : 'application/x-www-form-urlencoded' }
58
+ params = { 'grant_type' : 'urn:ibm:params:oauth:grant-type:apikey' , 'apikey' : ibmcloud_api_key }
59
+ resp = httpx .post ('https://iam.cloud.ibm.com/identity/token' , data = params , headers = hdrs )
60
+ resp .raise_for_status ()
61
+ response_json = resp .json ()
62
+ iam_token = response_json ['access_token' ]
63
+ return iam_token
64
+
65
+ except httpx .HTTPError as e :
66
+ logging .error ("HTTP exception {}." .format (str (e )))
67
+ sys .exit (1 )
68
+
69
+ def send_log_to_ibm_cloud_logs (application_name , subsystem_name , computer_name , message ):
70
+ iam_token = get_iam_token ()
71
+ if not iam_token :
72
+ raise ValueError ("IAM_TOKEN environment variable not found" )
73
+
74
+ log_data = [{
75
+ "applicationName" : application_name ,
76
+ "subsystemName" : subsystem_name ,
77
+ "computerName" : computer_name ,
78
+ "text" : {"message" : message },
79
+ "category" : "cat-1" ,
80
+ "className" : "class-1" ,
81
+ "methodName" : "method-1" ,
82
+ "threadId" : "thread-1"
83
+ }]
84
+
85
+ logging_url = os .environ .get ('LOGGING_URL' )
86
+ hdrs = { 'Content-Type' : 'application/json' , "Authorization" : f"{ iam_token } " }
87
+ resp = httpx .post (logging_url , data = json .dumps (log_data ), headers = hdrs )
88
+ resp .raise_for_status ()
89
+ print (resp .text )
90
+
91
+
92
+
93
+
53
94
@click .group ()
54
95
def cli ():
55
96
"""Group to hold our commands"""
@@ -71,6 +112,7 @@ def stop_vpc_instances():
71
112
if instance_name not in ignore_group :
72
113
print (f"Stopping instance { instance_name } " )
73
114
response = client .create_instance_action (instance_id = instance_id , type = 'stop' ).get_result ()
115
+ send_log_to_ibm_cloud_logs ("ce-start-stop-script" , "stop-action" , f"{ instance_name } " , f"Stopping instance { instance_name } " )
74
116
logging .info (response )
75
117
except ApiException as e :
76
118
print ("Failed to stop instances: %s\n " % e )
@@ -90,6 +132,7 @@ def start_vpc_instances():
90
132
instance_name = instance ['name' ]
91
133
92
134
print (f"Starting instance { instance_name } " )
135
+ send_log_to_ibm_cloud_logs ("ce-start-stop-script" , "start-action" , f"{ instance_name } " , f"Starting instance { instance_name } " )
93
136
response = client .create_instance_action (instance_id = instance_id , type = 'start' ).get_result ()
94
137
logging .info (response )
95
138
0 commit comments