|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +import Foundation |
| 19 | +import Dispatch |
| 20 | +#if canImport(FoundationNetworking) |
| 21 | +import FoundationNetworking |
| 22 | +#endif |
| 23 | + |
| 24 | +class Whisk { |
| 25 | + |
| 26 | + static var baseUrl = ProcessInfo.processInfo.environment["__OW_API_HOST"] |
| 27 | + static var apiKey = ProcessInfo.processInfo.environment["__OW_API_KEY"] |
| 28 | + // This will allow user to modify the default JSONDecoder and JSONEncoder used by epilogue |
| 29 | + static var jsonDecoder = JSONDecoder() |
| 30 | + static var jsonEncoder = JSONEncoder() |
| 31 | + |
| 32 | + class func invoke(actionNamed action : String, withParameters params : [String:Any], blocking: Bool = true) -> [String:Any] { |
| 33 | + let parsedAction = parseQualifiedName(name: action) |
| 34 | + let strBlocking = blocking ? "true" : "false" |
| 35 | + let path = "/api/v1/namespaces/\(parsedAction.namespace)/actions/\(parsedAction.name)?blocking=\(strBlocking)" |
| 36 | + |
| 37 | + return sendWhiskRequestSyncronish(uriPath: path, params: params, method: "POST") |
| 38 | + } |
| 39 | + |
| 40 | + class func trigger(eventNamed event : String, withParameters params : [String:Any]) -> [String:Any] { |
| 41 | + let parsedEvent = parseQualifiedName(name: event) |
| 42 | + let path = "/api/v1/namespaces/\(parsedEvent.namespace)/triggers/\(parsedEvent.name)?blocking=true" |
| 43 | + |
| 44 | + return sendWhiskRequestSyncronish(uriPath: path, params: params, method: "POST") |
| 45 | + } |
| 46 | + |
| 47 | + class func createTrigger(triggerNamed trigger: String, withParameters params : [String:Any]) -> [String:Any] { |
| 48 | + let parsedTrigger = parseQualifiedName(name: trigger) |
| 49 | + let path = "/api/v1/namespaces/\(parsedTrigger.namespace)/triggers/\(parsedTrigger.name)" |
| 50 | + return sendWhiskRequestSyncronish(uriPath: path, params: params, method: "PUT") |
| 51 | + } |
| 52 | + |
| 53 | + class func createRule(ruleNamed ruleName: String, withTrigger triggerName: String, andAction actionName: String) -> [String:Any] { |
| 54 | + let parsedRule = parseQualifiedName(name: ruleName) |
| 55 | + let path = "/api/v1/namespaces/\(parsedRule.namespace)/rules/\(parsedRule.name)" |
| 56 | + let params = ["trigger":triggerName, "action":actionName] |
| 57 | + return sendWhiskRequestSyncronish(uriPath: path, params: params, method: "PUT") |
| 58 | + } |
| 59 | + |
| 60 | + // handle the GCD dance to make the post async, but then obtain/return |
| 61 | + // the result from this function sync |
| 62 | + private class func sendWhiskRequestSyncronish(uriPath path: String, params : [String:Any], method: String) -> [String:Any] { |
| 63 | + var response : [String:Any]! |
| 64 | + |
| 65 | + let queue = DispatchQueue.global() |
| 66 | + let invokeGroup = DispatchGroup() |
| 67 | + |
| 68 | + invokeGroup.enter() |
| 69 | + queue.async { |
| 70 | + postUrlSession(uriPath: path, params: params, method: method, group: invokeGroup) { result in |
| 71 | + response = result |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + // On one hand, FOREVER seems like an awfully long time... |
| 76 | + // But on the other hand, I think we can rely on the system to kill this |
| 77 | + // if it exceeds a reasonable execution time. |
| 78 | + switch invokeGroup.wait(timeout: DispatchTime.distantFuture) { |
| 79 | + case DispatchTimeoutResult.success: |
| 80 | + break |
| 81 | + case DispatchTimeoutResult.timedOut: |
| 82 | + break |
| 83 | + } |
| 84 | + |
| 85 | + return response |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | + /** |
| 90 | + * Using new UrlSession |
| 91 | + */ |
| 92 | + private class func postUrlSession(uriPath: String, params : [String:Any], method: String,group: DispatchGroup, callback : @escaping([String:Any]) -> Void) { |
| 93 | + |
| 94 | + guard let encodedPath = uriPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { |
| 95 | + callback(["error": "Error encoding uri path to make openwhisk REST call."]) |
| 96 | + return |
| 97 | + } |
| 98 | + |
| 99 | + let urlStr = "\(baseUrl!)\(encodedPath)" |
| 100 | + if let url = URL(string: urlStr) { |
| 101 | + var request = URLRequest(url: url) |
| 102 | + request.httpMethod = method |
| 103 | + |
| 104 | + do { |
| 105 | + request.addValue("application/json", forHTTPHeaderField: "Content-Type") |
| 106 | + request.httpBody = try JSONSerialization.data(withJSONObject: params) |
| 107 | + |
| 108 | + let loginData: Data = apiKey!.data(using: String.Encoding.utf8, allowLossyConversion: false)! |
| 109 | + let base64EncodedAuthKey = loginData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) |
| 110 | + request.addValue("Basic \(base64EncodedAuthKey)", forHTTPHeaderField: "Authorization") |
| 111 | + let session = URLSession(configuration: URLSessionConfiguration.default) |
| 112 | + |
| 113 | + let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in |
| 114 | + |
| 115 | + // exit group after we are done |
| 116 | + defer { |
| 117 | + group.leave() |
| 118 | + } |
| 119 | + |
| 120 | + if let error = error { |
| 121 | + callback(["error":error.localizedDescription]) |
| 122 | + } else { |
| 123 | + |
| 124 | + if let data = data { |
| 125 | + do { |
| 126 | + //let outputStr = String(data: data, encoding: String.Encoding.utf8) as String! |
| 127 | + //print(outputStr) |
| 128 | + let respJson = try JSONSerialization.jsonObject(with: data) |
| 129 | + if respJson is [String:Any] { |
| 130 | + callback(respJson as! [String:Any]) |
| 131 | + } else { |
| 132 | + callback(["error":" response from server is not a dictionary"]) |
| 133 | + } |
| 134 | + } catch { |
| 135 | + callback(["error":"Error creating json from response: \(error)"]) |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + }) |
| 140 | + |
| 141 | + task.resume() |
| 142 | + } catch { |
| 143 | + callback(["error":"Got error creating params body: \(error)"]) |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + // separate an OpenWhisk qualified name (e.g. "/whisk.system/samples/date") |
| 149 | + // into namespace and name components |
| 150 | + private class func parseQualifiedName(name qualifiedName : String) -> (namespace : String, name : String) { |
| 151 | + let defaultNamespace = "_" |
| 152 | + let delimiter = "/" |
| 153 | + |
| 154 | + let segments :[String] = qualifiedName.components(separatedBy: delimiter) |
| 155 | + |
| 156 | + if segments.count > 2 { |
| 157 | + return (segments[1], Array(segments[2..<segments.count]).joined(separator: delimiter)) |
| 158 | + } else if segments.count == 2 { |
| 159 | + // case "/action" or "package/action" |
| 160 | + let name = qualifiedName.hasPrefix(delimiter) ? segments[1] : segments.joined(separator: delimiter) |
| 161 | + return (defaultNamespace, name) |
| 162 | + } else { |
| 163 | + return (defaultNamespace, segments[0]) |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | +} |
0 commit comments