<commit_before>(comment 
  Celestial, Copyright 2012 <NAME>, n<EMAIL>
  Licensed under the Apache License,
  Version 2.0  (the "License") you may not use this file except in compliance with the License.
  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.)

(ns kvm.provider
  (:require 
    [kvm.validations :refer (provider-validation)]
    [clojure.core.strint :refer (<<)] 
    [kvm.clone :refer (clone-domain domain-zip)]
    [kvm.disks :refer (clear-volumes)]
    [kvm.common :refer (connect get-domain state)]
    [supernal.sshj :refer (ssh-up?)]
    [celestial.core :refer (Vm)] 
    [taoensso.timbre :as timbre]
    [celestial.persistency.systems :as s]
    [celestial.provider :refer (mappings selections transform os->template wait-for wait-for-ssh)]
    [celestial.model :refer (translate vconstruct hypervisor*)])
  (:import org.libvirt.LibvirtException))

(timbre/refer-timbre)

(defn connection [{:keys [host username port]}] 
  (connect (<< "qemu+ssh://~{username}@~{host}:~{port}/system")))

(defmacro with-connection [& body]
  `(let [~'connection (connection ~'node)] (do ~@body)))

(defn wait-for-status [instance req-stat timeout]
  "Waiting for ec2 machine status timeout is in mili"
  (wait-for {:timeout timeout} #(= req-stat (.status instance))
    {:type ::kvm:status-failed :status req-stat :timeout timeout} 
      "Timed out on waiting for status"))


(defrecord Domain [system-id node domain]
  Vm
  (create [this]
    (with-connection 
      (let [image (get-in domain [:image :template]) target (select-keys domain [:name :cpu :ram])]
        (clone-domain connection image target)
        (wait-for-status this "running" [5 :minute])
         this 
        ))) 

  (delete [this]
    (with-connection 
      (clear-volumes connection (domain-zip connection (domain :name)))
      (.undefine (get-domain connection (domain :name))))
    )

  (start [this]
    (with-connection 
      (when-not (= (.status this) "running")
        (.create (get-domain connection (domain :name))))))

  (stop [this]
    (with-connection 
      (.destroy (get-domain connection (domain :name)))
      (wait-for-status this "shutoff" [5 :minute])
      ))

  (status [this]
    (with-connection 
      (try 
        (state (get-domain connection (domain :name)))
          (catch LibvirtException e (debug (.getMessage e)) false))))

  (ip [this]))

(defn machine-ts 
  "Construcuting machine transformations"
  [{:keys [hostname domain] :as machine}]
   {:name (fn [hostname] (<< "~{hostname}.~{domain}")) 
    :image (fn [os] ((os->template :kvm) os))})

(defmethod translate :kvm [{:keys [machine kvm] :as spec}] 
   (-> machine
     (mappings {:os :image :hostname :name})
     (transform (machine-ts machine))
     (selections [[:name :user :image :cpu :ram]])))

(defmethod vconstruct :kvm [{:keys [kvm machine system-id] :as spec}]
   (let [[domain] (translate spec) {:keys [node]} kvm]
     (provider-validation domain)
     (->Domain system-id (hypervisor* :kvm :nodes node) domain)))

(ns kvm.common
 (:require [clojure.zip :as zip])
 (:import 
    java.text.SimpleDateFormat
    org.libvirt.Connect))

(defn connect 
   "Connecting" 
   [uri]
   (Connect. uri))

(defn tree-edit
  "Take a zipper, a function that matches a pattern in the tree,
   and a function that edits the current location in the tree.  Examine the tree
   nodes in depth-first order, determine whether the matcher matches, and if so
   apply the editor."
  [zipper matcher editor]
  (loop [loc zipper]
    (if (zip/end? loc)
      (zip/root loc)
      (if-let [matcher-result (matcher loc)]
        (let [new-loc (zip/edit loc editor)]
          (if (not (= (zip/node new-loc) (zip/node loc)))
            (recur (zip/next new-loc))))
        (recur (zip/next loc))))))

(defn get-domain [c name] 
   (.domainLookupByName c name))

(defn domain-list
   [c]
   (map (partial get-domain c) (.listDefinedDomains c)))

(defn state [domain]
  (let [s (.toString (.state (.getInfo domain)))]
    (.toLowerCase (.replace s "VIR_DOMAIN_" ""))))
<commit_msg>fixing wrong license paste<commit_after>(comment 
  Celestial, Copyright 2012 <NAME>, n<EMAIL>
  Licensed under the Apache License,
  Version 2.0  (the "License") you may not use this file except in compliance with the License.
  You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.)

(ns kvm.common
  (:require [clojure.zip :as zip])
  (:import 
     java.text.SimpleDateFormat
     org.libvirt.Connect))

(defn connect 
   "Connecting" 
   [uri]
   (Connect. uri))

(defn tree-edit
  "Take a zipper, a function that matches a pattern in the tree,
   and a function that edits the current location in the tree.  Examine the tree
   nodes in depth-first order, determine whether the matcher matches, and if so
   apply the editor."
  [zipper matcher editor]
  (loop [loc zipper]
    (if (zip/end? loc)
      (zip/root loc)
      (if-let [matcher-result (matcher loc)]
        (let [new-loc (zip/edit loc editor)]
          (if (not (= (zip/node new-loc) (zip/node loc)))
            (recur (zip/next new-loc))))
        (recur (zip/next loc))))))

(defn get-domain [c name] 
   (.domainLookupByName c name))

(defn domain-list
   [c]
   (map (partial get-domain c) (.listDefinedDomains c)))

(defn state [domain]
  (let [s (.toString (.state (.getInfo domain)))]
    (.toLowerCase (.replace s "VIR_DOMAIN_" ""))))

{'fraction_non_alphanumeric': 0.1329919048405749, 'fraction_numerical': 0.0031389393689079796, 'mean_word_length': 3.3335719398711525, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3261653', 'n_tokens_mistral': 1968, 'n_tokens_neox': 1901, 'n_words': 662}